如何在C#中通过套接字发送字符串

Lol*_*ewn 5 c# sockets string

我在本地测试它,所以连接的IP可以 localhost or 127.0.0.1

发送后,它会收到一个字符串.这也很方便.

Lol*_*ewn 16

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);
Run Code Online (Sandbox Code Playgroud)

用于连接它.要发送一些东西:

//Start sending stuf..
byte[] byData = System.Text.Encoding.ASCII.GetBytes("un:" + username + ";pw:" + password);
soc.Send(byData);
Run Code Online (Sandbox Code Playgroud)

并回读..

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);
Run Code Online (Sandbox Code Playgroud)

  • 请注意,套接字中没有分隔符,因此发送0123456789可能会导致必须读取一次,两次,三次...即读取0123后跟456789一天和01234567与89另一个,和0123456789对不同的尝试与单个读.数据越大,读取时分割的可能性越大. (2认同)
  • 是否有任何理由为什么`soc.Connect(remoteEP);`将无法连接`127.0.0.1`与`无法建立连接,因为目标机器主动拒绝它'? (2认同)