服务器端的发送按钮不工作TCP C#

时间:2016-12-20 19:28:14

标签: c# asynchronous tcp

我尝试在我的服务器中添加发送按钮以将数据发送到客户端连接工作得很好,并且客户端中的发送按钮也正常工作,连接启动时发送数据但是当我尝试在按钮下添加代码时发送_click我收到这条消息: 由于套接字未连接,因此不允许发送或接收数据的请求。 这里是服务器端代码"

 public partial class Server : Form
{
    public Server()
    {
        InitializeComponent();

        ListBox.CheckForIllegalCrossThreadCalls = false;
        // call server connection method
        connection();
    }


    private Socket _server;
    Socket _client;
    private byte [] _buffer = new byte[1024];
    private Socket client;
    Socket oldConnection;


    /**
     * Server Connection Binding and listening method
     */
    private void connection()
    {
        _server = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);
        try
        {
            _server.Bind(new IPEndPoint(IPAddress.Any, 5020));
            _server.Listen(5);
            // before connecting to any client
            status.Items.Add("Waiting for client...");

            _server.BeginAccept(new AsyncCallback(AcceptConn), _server);
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    // Accept Clients Connections
    private void AcceptConn(IAsyncResult iar)
    {
        try
        {
            oldConnection = (Socket)iar.AsyncState;
            client = (Socket)oldConnection.EndAccept(iar);
            // if the socket status is connected
            // add
            // Connected to: clientIP:Portnumber
            status.Items.Add("Connected to: " + client.RemoteEndPoint.ToString());
            // welcom message from server
            string welcome = "Welcome to my server";
            byte[] welcomeMessage = Encoding.ASCII.GetBytes(welcome);

            client.BeginSend(welcomeMessage, 0, welcomeMessage.Length,
                SocketFlags.None, new AsyncCallback(SendData), client);

            // Accept next client Connection
            oldConnection.BeginAccept(new AsyncCallback(AcceptConn),oldConnection);
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    // create Send callback method to execute the BeginSend() call
    private void SendData(IAsyncResult iar)
    {
        try
        {
            _client = (Socket)iar.AsyncState;
            int sent = _client.EndSend(iar);

            _client.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, 
                new AsyncCallback(ReceiveData), _client);
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    // create Receive callback method to execute the BeginReceive() call
    private void ReceiveData(IAsyncResult iar)
    {
        try
        {
            Socket client = (Socket)iar.AsyncState;
            int recv = client.EndReceive(iar);

            if (recv == 0)
            {
                // updating status
                status.Items.Add("Waiting for client...");
                // _server Socket will start Accepting new clients connections
                _server.BeginAccept(new AsyncCallback(AcceptConn), _server);
                return;
            }
            else
            { 
                string receivedData = Encoding.ASCII.GetString(_buffer, 0, recv);
                // add message to the ListBox
                results.Items.Add(receivedData);
                // resend client message to the client
                byte[] message2 = Encoding.ASCII.GetBytes(receivedData);

                client.BeginSend(message2, 0, message2.Length, SocketFlags.None,
                    new AsyncCallback(SendData), client);
            }
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void Server_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            byte[] strMessage = Encoding.ASCII.GetBytes("Server Sending ..");
            client.BeginSend(strMessage, 0, strMessage.Length, SocketFlags.None,
                new AsyncCallback(SendData), client);
            MessageBox.Show("done");

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}
}

我正在使用异步TCP C#。

1 个答案:

答案 0 :(得分:0)

您的服务器已设置为接受多个客户端。你应该有一个单独的套接字来接受。一旦客户端被接受,您可以将其复制到另一个套接字对象并将其添加到List<socket>中,然后重置接受的套接字以进行下一次连接。目前,您尝试将消息发送到已重置为接受下一个客户端的套接字,因此您收到错误。存储连接的套接字并具有单独的套接字以进行接受后,您的发送事件可以将消息发送到存储在列表中的套接字或所有套接字。

var clients = new List<socket>();

....

 private void AcceptConn(IAsyncResult iar)
    {
        try
        {
            oldConnection = (Socket)iar.AsyncState;            
            var clientSocket = (Socket)oldConnection.EndAccept(iar);
            clients.Add(clientSocket);
....