通过网络C#发送数据 [英] Send data over the network C#

查看:70
本文介绍了通过网络C#发送数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试通过网络发送一个字符串,这是我的代码:

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

当我运行它时,我得到了System.Net.Sockets.SocketException

When I run it I got System.Net.Sockets.SocketException

推荐答案

如果使用的是无连接协议,则必须在调用Send之前先调用Connect,否则Send将抛出SocketException.如果使用的是面向连接的协议,则必须使用连接"建立远程主机连接,或者使用接受"接受传入的连接. 请参考 Socket.Send方法(字节[],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,

string response = "Hello";
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");

if (ipAddress != null)
{
    IPEndPoint serverEndPoint = new IPEndPoint(ipAddress, 25);
    byte[] receiveBuffer = new byte[100];

    try
    {
        using (TcpClient client = new TcpClient(serverEndPoint))
        {
            using (Socket socket = client.Client)
            {
                socket.Connect(serverEndPoint);

                byte[] data = Encoding.ASCII.GetBytes(response);

                socket.Send(data, data.Length, SocketFlags.None);

                socket.Receive(receiveBuffer);

                Console.WriteLine(Encoding.ASCII.GetString(receiveBuffer));
            }
        }
    }
    catch (SocketException socketException)
    {
        Console.WriteLine("Socket Exception : ", socketException.Message);
        throw;
    }
}

下次,尝试添加异常消息以说明实际出了什么问题.

Next time, try including the exception message to explain what actually went wrong.

这篇关于通过网络C#发送数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆