通过网络发送数据C#

时间:2010-12-12 21:22:00

标签: c# network-programming

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

 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

1 个答案:

答案 0 :(得分:3)

如果您使用的是无连接协议,则必须在调用Send之前调用Connect,否则Send将抛出SocketException。如果使用面向连接的协议,则必须使用“连接”建立远程主机连接,或使用“接受”接受传入连接。 请参阅Socket.Send Method (Byte[], Int32, SocketFlags)

假设您使用的是无连接协议,代码应该是这样的,

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

下次尝试包含异常消息以解释实际出现的问题。