简体   繁体   English

使用C#将TCP数据发送到特定的TcpClient

[英]Send TCP data to specfic TcpClient in C#

I'm getting an error that the TcpClient isn't connected and I can't send information to a socket that is not active. 我收到一个错误消息,提示TcpClient未连接,并且无法将信息发送到未激活的套接字。 I'm wondering what's wrong with this code? 我想知道这段代码怎么了? ERROR: This type of connection is not allowed on non-connected sockets. 错误:未连接的套接字上不允许这种类型的连接。

SERVER:
public List<TcpClient> clients = new List<TcpClient>();

  On client connection:
  Socket s = currClient.Client;
  clients.Add(currClient.Client);

When Sending Client Info
   Stream sendData = clients[0].GetStream();
        ASCIIEncoding text = new ASCIIEncoding();
        byte[] clientInfoByte = text.GetBytes("msg");
        sendData.Write(clientInfoByte, 0, clientInfoByte.Length);
        sendData.Close();

CLIENT: 客户:

        Thread thr = new Thread(commands);
        thr.Start();
    }
    public static void commands()
    {
        Stream cmds = me.GetStream();
        while (true)
        {
            byte[] b = new byte[100];
            Socket s = me.Client;
            int k = s.Receive(b);
            string ClientInfo = "";
            string command = System.Text.Encoding.ASCII.GetString(b);

            if (command == "msg")
            {
                MessageBox.Show("Command Recieved!");
            }
        }
    }

In your server create a TcpListener "listener" and accept incoming connections using: 在您的服务器中,创建一个TcpListener“ listener”并使用以下命令接受传入的连接:

listener.BeginAcceptTcpClient(
    new AsyncCallback(DoAcceptTcpClientCallback), 
    listener);

Then in your callback you get your TcpClient to send data to 然后在回调中,您将TcpClient发送到

// Process the client connection.       
public static void DoAcceptTcpClientCallback(IAsyncResult ar) 
{
    TcpListener listener = (TcpListener) ar.AsyncState;

    TcpClient client = listener.EndAcceptTcpClient(ar);

    //add to your client list
    clients.Add(client);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM