【问题标题】:Sending a string to a server from a client in C#在 C# 中从客户端向服务器发送字符串
【发布时间】:2011-06-25 10:12:51
【问题描述】:

我正在编写一个简单的测试程序,将字符串从客户端发送到服务器,然后在服务器程序上显示文本。我该怎么做呢。

这是我的客户端代码。

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


    }


}

【问题讨论】:

    标签: c# sockets networking client


    【解决方案1】:

    您可以在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.SendTimeout & Socket.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 字节块中的数据,只要 sunIsBurning,解码为 UTF-8”。这意味着对方发送的数据必须是UTF-8,否则你会得到一个异常(它应该被你捕获)这也意味着服务器只会在连接失败时停止接收。

    如果您收到 15 个字节,并且客户端终止连接,则永远不会打印这 15 个字节。您将需要更好的错误处理:)

    在大多数情况下,未捕获的异常会杀死您的应用程序;不适合服务器。

    “连接失败”可能表示a lot of things,可能是连接被对等方重置或您的网卡着火了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-02
      • 2014-03-10
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多