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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8773721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 04:22:42  来源:igfitidea点击:

How to send a string over a socket in C#

c#stringsockets

提问by Lolmewn

I am testing this locally, so the IP to connect to can be localhost or 127.0.0.1

我正在本地测试这个,所以要连接的 IP 可以是 localhost or 127.0.0.1

After sending it, it receives a string back. That would also be handy.

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

采纳答案by Lolmewn

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);

For connecting to it. To send something:

用于连接到它。发送东西:

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

And for reading back..

而为了回读..

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);

回答by Masoud Siahkali

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAdd = System.Net.IPAddress.Parse(m_ip);
IPEndPoint remoteEP = new IPEndPoint(ipAdd, m_port);

socket.Connect(remoteEP);

byte[] byData = System.Text.Encoding.ASCII.GetBytes("Message");
socket.Send(byData);


socket.Disconnect(false);
socket.Close();