C#套接字程序

本文关键字:程序 套接字 | 更新日期: 2023-09-27 18:20:35

你好,我正在用C#做一个套接字程序,现在我遇到了一个问题。我使用这个服务器程序代码和我一直在寻找的客户端代码。我已经修改了一些。所以我遇到的问题是,我确实希望能够断开与服务器的连接,我一直在尝试和谷歌搜索它,但找不到如何做到这一点。使用这些代码有什么简单的方法??

客户端代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
namespace soket_client_delen
{
public partial class Form1 : Form
{
    System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
    public Form1()
    {
        InitializeComponent();
        this.textBox2.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CheckKeys);
    }
    private void CheckKeys(object sender, System.Windows.Forms.KeyPressEventArgs e)
    {
        if (e.KeyChar == (char)13)
        {
            // Then Enter key was pressed
            if (checkBox1.Checked ==true)
                send();
        }
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        msg("Client Started");
        clientSocket.Connect("127.0.0.1", 8888);
        label1.Text = "Client Socket Program - Server Connected ...";
    }

    private void button1_Click_1(object sender, EventArgs e)
    {
        send();
    }
    public void send()
    {
        NetworkStream serverStream = clientSocket.GetStream();
        byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text +"$");
        textBox2.Text = "";
        serverStream.Write(outStream, 0, outStream.Length);
        serverStream.Flush();
        byte[] inStream = new byte[10025];
        serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
        string returndata = System.Text.Encoding.ASCII.GetString(inStream);
        msg("Data from Server : " + returndata);
    }

    public void msg(string mesg)
    {
        textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + mesg;
    }
    private void button2_Click(object sender, EventArgs e)
    {
    }
}
}

服务器代码:

using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace soket_serverdelen
{
class Program
{
    static void Main(string[] args)
    {
        TcpListener serverSocket = new TcpListener(8888);
        TcpClient clientSocket = default(TcpClient);
        int counter = 0;
        serverSocket.Start();
        Console.WriteLine(" >> " + "Server Started");
        counter = 0;
        while (true)
        {
            counter += 1;
            clientSocket = serverSocket.AcceptTcpClient();
            Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
            handleClinet client = new handleClinet();
            client.startClient(clientSocket, Convert.ToString(counter));
        }
        clientSocket.Close();
        serverSocket.Stop();
        Console.WriteLine(" >> " + "exit");
        Console.ReadLine();
    }
}
//Class to handle each client request separatly
public class handleClinet
{
    TcpClient clientSocket;
    string clNo;
    public void startClient(TcpClient inClientSocket, string clineNo)
    {
        this.clientSocket = inClientSocket;
        this.clNo = clineNo;
        Thread ctThread = new Thread(doChat);
        ctThread.Start();
    }
    private void doChat()
    {
        int requestCount = 0;
        byte[] bytesFrom = new byte[10025];
        string dataFromClient = null;
        Byte[] sendBytes = null;
        string serverResponse = null;
        string rCount = null;
        requestCount = 0;
        while ((true))
        {
            try
            {
                requestCount = requestCount + 1;
                NetworkStream networkStream = clientSocket.GetStream();
                networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
                dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                    rCount = Convert.ToString(requestCount);
                    serverResponse = "Server to clinet(" + clNo + ") " + rCount;
                    sendBytes = Encoding.ASCII.GetBytes(serverResponse);
                    networkStream.Write(sendBytes, 0, sendBytes.Length);
                    networkStream.Flush();
                    Console.WriteLine(" >> " + serverResponse);
            }
            catch (Exception ex)
            {
                Console.WriteLine(" >> " + ex.ToString());
            }
        }
    }
}
}

感谢您的帮助

C#套接字程序

您尝试过clientSocket.Close()吗?http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.close.aspx

您需要让双方都调用close。通常,虽然不是硬性规定,但客户端会终止连接,服务器端会对此做出响应。因此,当您的客户端完成发送/接收时,客户端会调用关闭。然后服务器端对此作出响应,并在其端调用close。

对于客户端:

NetworkStream ns = clientSocket.GetStream();
// send important stuff
// receive important stuff from server
ns.Close();

对于服务器端:

NetworkStream ns = clientSocket.GetStream();
int bytesRead;
while((bytesRead = ns.Read(buffer, 0, buffer.Length)) >= 0) {
    if(bytesRead > 0) {
        // do really important stuff
    } else if(bytesRead == 0) {
        // client has trasmitted FIN packet, close and exit thread
        ns.Close();
    } else {
        // handle error condition
        // probably close the connection
    }
}

上面的代码只是一个模型。我还没有测试过。你正在使用网络流,所以这个例子(我认为)应该会有所帮助。我通常使用select()(来自windows API,.NET在Socket类中公开它)来完成这项工作。基本上,当任何一方通过Close()关闭连接时,Windows TCP堆栈都会发送一个TCP FIN数据包。这表示始发侧希望关闭连接。此外,有人评论说,您应该将这些流的使用包装在using子句中。如果您不打算直接调用Close(),那么这是必须的。

通常客户端会向服务器发送注销信号。收到此消息后,服务器将关闭连接。客户端应运行一个循环,直到serverStream.Socket.Closed=True,然后再退出。