通过网络发送数据 C#
我尝试通过网络发送一个字符串,这是我的代码:
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 25);
TcpClient client = new TcpClient(serverEndPoint);
Socket socket = client.Client;
byte[] data = Encoding.ASCII.GetBytes(response);
socket.Send(data, data.Length, SocketFlags.None);
socket.Close();
client.Close();
当我运行它时,我得到 System.Net.Sockets.SocketException
I try to send a string over the network, this is my code:
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 25);
TcpClient client = new TcpClient(serverEndPoint);
Socket socket = client.Client;
byte[] data = Encoding.ASCII.GetBytes(response);
socket.Send(data, data.Length, SocketFlags.None);
socket.Close();
client.Close();
When I run it I got System.Net.Sockets.SocketException
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果使用无连接协议,则必须在调用 Send 之前调用 Connect,否则 Send 将抛出 SocketException。如果您使用面向连接的协议,则必须使用 Connect 建立远程主机连接,或使用 Accept 接受传入连接。
请参阅 Socket.Send 方法(Byte[]、Int32、SocketFlags)
假设如果您使用的是无连接协议,代码应该是这样的,
下次,尝试包含异常消息来解释实际出了什么问题。
If you are using a connectionless protocol, you must call Connect before calling Send, or Send will throw a SocketException. If you are using a connection-oriented protocol, you must either use Connect to establish a remote host connection, or use Accept to accept an incoming connection.
Refer Socket.Send Method (Byte[], Int32, SocketFlags)
Assuming you are using a connectionless protocol the code should be like this,
Next time, try including the exception message to explain what actually went wrong.