我在本地测试,所以要连接的 IP 可以是 localhost 或 127.0.0.1
发送后,它会收到一个字符串。那也很方便。
最佳答案
Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(server);
System.Net.IPEndPoint remoteEP = new IPEndPoint(ipAdd, 3456);
soc.Connect(remoteEP);
用于连接它。 发送一些东西:
//Start sending stuf..
byte[] byData = System.Text.Encoding.ASCII.GetBytes("un:" + username + ";pw:" + password);
soc.Send(byData);
为了回读..
byte[] buffer = new byte[1024];
int iRx = soc.Receive(buffer);
char[] chars = new char[iRx];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(buffer, 0, iRx, chars, 0);
System.String recv = new System.String(chars);
关于c# - 如何在 C# 中通过套接字发送字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8773721/