在C#中从客户端向服务器发送字符串

5
我将使用一段简单的测试程序来实现客户端向服务器发送字符串,然后在服务器程序上显示文本。具体该如何操作呢?
以下是客户端代码:
using System;
using System.Net;
using System.Net.Sockets;


    class client
    {

        static String hostName = Dns.GetHostName();

        public static void Main(String[] args)
        {
            String test = Console.ReadLine();

            IPHostEntry ipEntry = Dns.GetHostByName(hostName);
            IPAddress[] addr = ipEntry.AddressList;

            //The first one in the array is the ip address of the hostname
           IPAddress ipAddress = addr[0];


            TcpClient client = new TcpClient();

            //First parameter is Hostname or IP, second parameter is port on which server is listening
            client.Connect(ipAddress, 8);


            client.Close();
        }
    }

这是我的服务器代码

using System;
using System.Net;
using System.Net.Sockets;

class server
{
    static int port = 8;
    static String hostName = Dns.GetHostName();
    static IPAddress ipAddress;

    public static void Main(String[] args)
    {
        IPHostEntry ipEntry = Dns.GetHostByName(hostName);

        //Get a list of possible ip addresses
        IPAddress[] addr = ipEntry.AddressList;

        //The first one in the array is the ip address of the hostname
        ipAddress = addr[0];

        TcpListener server = new TcpListener(ipAddress,port);

        Console.Write("Listening for Connections on " + hostName + "...\n");

        //start listening for connections
        server.Start();

        //Accept the connection from the client, you are now connected
        Socket connection = server.AcceptSocket();

        Console.Write("You are now connected to the server\n\n");


        int pauseTime = 10000;
        System.Threading.Thread.Sleep(pauseTime);

        connection.Close();


    }


}
1个回答

8
您可以在Socket上使用SendReceive方法。也有异步版本,可以通过BeginSomethingEndSomething方法实现。
您需要选择一种协议来发送原始字节,即使是简单的协议也可以。要发送一些文本,请选择一种编码(我会使用UTF-8)并使用Encoding.GetBytes获取原始字节。
示例:
Byte[] bytes = Encoding.UTF8.GetBytes("Royale With Cheese");

UTF8是Encoding类的静态属性,它为您提供方便。

然后,您可以使用以下方式将数据发送到服务器/客户端:

int sent = connection.Send(bytes);

收到:
Byte[] bytes = new Bytes[100]; 
int received = connection.Receive(bytes);

这看起来很简单,但有一些注意事项。连接可能随时断开,因此您必须准备好异常处理,特别是SocketException。另外,如果您查看示例,可以看到我有两个变量sentreceived。它们保存了SendReceive实际发送的字节数。您不能依赖套接字发送或接收所有数据(尤其是在接收时,如果对方发送的比您预期的少怎么办?)
一种方法是循环发送,直到所有数据都被指示为已发送:
var bytes = Encoding.UTF8.GetBytes("Royale With Cheese");
int count = 0;
while (count < bytes.Length) // if you are brave you can do it all in the condition.
{
    count += connection.Send(
        bytes, 
        count, 
        bytes.Length - count, // This can be anything as long as it doesn't overflow the buffer, bytes.
        SocketFlags.None)
}

SendReceive是同步的,它们会阻塞直到发送或接收到数据。你应该在套接字上设置一些超时值(Socket.SendTimeoutSocket.ReceiveTimeout)。默认值为0,这意味着它们可能会永远阻塞。

那么接收方呢?让我们尝试做一个类似的循环。

int count = 0;
var bytes = new Byte[100];
do
{
    count += connection.Receive(
        bytes,
        count,
        bytes.Length - count,
        SocketFlags.None);
} while (count < bytes.Length);

嗯。那么……如果客户端发送少于100个字节会发生什么?如果有超时,我们将会阻塞直到超时结束,或者客户端发送足够的数据。如果客户端发送了多于100个字节,你只会得到前100个字节。

在您的情况下,我们可以尝试读取非常小的数据并打印。读取、打印、循环:

var sunIsBurning = true;
while (sunIsBurning) {
    var bytes = new Byte[16];
    int received = socket.Receive(bytes);
    if (received > 0)
        Console.Out.WriteLine("Got {0} bytes. START:{1}END;", received, Encoding.UTF8.GetString(bytes));
}

在这里,我们说“接收16字节的数据块,只要太阳还在燃烧,就解码为UTF-8”。这意味着其他一方发送的数据必须是UTF-8格式,否则您将会收到一个异常(它可能被您捕获)。这也意味着服务器只有在连接失败时才会停止接收。

如果您已经接收了15个字节,并且客户端关闭了连接,则这15个字节将永远不会被打印。您需要更好的错误处理来解决这个问题 :)

未捕获的异常在大多数情况下会导致应用程序崩溃;对于服务器而言并不理想。

“连接失败”可能意味着很多事情,可能是由同行重置连接或您的网络适配器着火引起的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接