将TCP数据发送到C#中的特定TcpClient
本文关键字:TcpClient TCP 数据 | 更新日期: 2023-09-27 18:19:28
我收到一个错误,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!");
}
}
}
在服务器中创建一个TcpListener"listener",并使用接受传入连接
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);
}