[英]Send TCP data to specfic TcpClient in C#
我收到一個錯誤消息,提示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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.