开发者

Send data over the network C#

开发者 https://www.devze.com 2023-01-30 00:14 出处:网络
I try to send a string over the network, this is my code: IPE开发者_开发技巧ndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(\"127.0.0.1\"), 25);

I try to send a string over the network, this is my code:

 IPE开发者_开发技巧ndPoint 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消