为什么我的TcpClient不发送信息? (C#)

时间:2014-08-26 04:49:51

标签: c# tcp tcpclient tcplistener

我正在制作一个简单的工具,告诉您客户端何时通过Tcp连接。由于某种原因,它不会在第一次运行程序时发送它,但它只是第二次发送它

例如:双击程序 - 没有 再次双击它,它运行TcpClient的东西。

我的代码告诉某人何时连接:

public void ListenForClients()
    {
        while (listening == true)
        {
            TcpClient currClient = listener.AcceptTcpClient();
            clients.Add(currClient);

            byte[] b = new byte[100];
            Socket s = listener.AcceptSocket();
            int k = s.Receive(b);
            string ClientInfo = "";
            for (int i = 0; i < k; i++)
            {
                ClientInfo = ClientInfo + Convert.ToChar(b[i]).ToString();
            }

            clientHandler(currClient, ClientInfo);
        }
    }

    public void clientHandler(TcpClient client, string ClientInfo)
    {
        clientID++;
        this.Invoke(new Action(() =>
            {
                this.Text = "Network Monitor - Connections: " + clientID.ToString();
            }));

        listView1.Invoke(new Action(() =>
            {

                IPEndPoint IP = ((IPEndPoint)client.Client.RemoteEndPoint);
                ListViewItem lvi = new ListViewItem(new string[] { clientID.ToString(), IP.ToString(), ClientInfo });
                this.listView1.Items.Add(lvi);
            }));
    }

我的客户端发送Tcp信息的代码

  TcpClient me = new TcpClient();
            me.Connect("127.0.0.1", 2222);
            Stream sendData = me.GetStream();
            ASCIIEncoding text = new ASCIIEncoding();
            byte[] clientInfoByte = text.GetBytes("lol");
            sendData.Write(clientInfoByte,0,clientInfoByte.Length);
            sendData.Close();
            me.Close();

1 个答案:

答案 0 :(得分:0)

尝试替换

Socket s = listener.AcceptSocket();

Socket s = currClient.Client;

注意:

for (int i = 0; i < k; i++)
{
    ClientInfo = ClientInfo + Convert.ToChar(b[i]).ToString();
}

可以写成

ClientInfo = System.Text.Encoding.ASCII.GetString(b);