【问题标题】:Send TCP data to specfic TcpClient in C#在 C# 中将 TCP 数据发送到特定的 TcpClient
【发布时间】:2014-08-27 23:25:44
【问题描述】:

我收到一个错误,提示 TcpClient 未连接,我无法将信息发送到未激活的套接字。我想知道这段代码有什么问题? 错误:在未连接的套接字上不允许这种类型的连接。

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();

客户:

        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!");
            }
        }
    }

【问题讨论】:

  • 您需要提供更多信息。 currClient 是什么?套接字上使用的地址/绑定是什么?
  • currClient 是当前的 TCPClient(它在连接时被命名)

标签: c# tcp tcpclient tcplistener


【解决方案1】:

在您的服务器中创建一个 TcpListener “侦听器”并使用以下命令接受传入连接:

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

然后在你的回调中让你的 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);
  }

【讨论】:

  • 这不起作用。我收到一个关于如何无法阻止套接字调用的错误消息。
  • 将 Client.Blocking 属性更改为 false。来自 MSDN:“如果您处于阻塞模式,并且您进行的方法调用未立即完成,您的应用程序将阻塞执行,直到请求的操作完成。如果您希望即使请求的操作未完成也继续执行,请更改将 Blocking 属性设置为 false。”
  • 同样的错误!我添加了 s.Blocking = false;它仍然给我说我正在阻止的错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-27
  • 1970-01-01
  • 1970-01-01
  • 2018-12-25
  • 1970-01-01
  • 2018-04-12
相关资源
最近更新 更多