使用套接字响应客户端? [英] Respond to a client using a socket?

查看:68
本文介绍了使用套接字响应客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个基本的控制台应用程序可以通过网络"进行通信,即使所有的通信都发生在我的本地机器上.

I have two basic console apps that communicate "over the network" even though all of the communication takes place on my local machine.

客户端代码:

public static void Main()
{
    while (true)
    {
        try
        {
            TcpClient client = new TcpClient();

            client.Connect("127.0.0.1", 500);

            Console.WriteLine("Connected.");

            byte[] data = ASCIIEncoding.ASCII.GetBytes(new FeederRequest("test", TableType.Event).GetXmlRequest().ToString());

            Console.WriteLine("Sending data.....");

            using (var stream = client.GetStream())
            {
                stream.Write(data, 0, data.Length);
                stream.Flush();

                Console.WriteLine("Data sent.");
            }

            client.Close();

            Console.ReadLine();
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.StackTrace);

            Console.ReadLine();
        }
    }
}

服务器代码:

public static void Main()
{
    try
    {
        IPAddress ipAddress = IPAddress.Parse("127.0.0.1");

        Console.WriteLine("Starting TCP listener...");

        TcpListener listener = new TcpListener(ipAddress, 500);

        listener.Start();

        Console.WriteLine("Server is listening on " + listener.LocalEndpoint);

        while (true)
        {
            Socket client = listener.AcceptSocket();

            Console.WriteLine("\nConnection accepted.");

            var childSocketThread = new Thread(() =>
                {
                    Console.WriteLine("Reading data...\n");

                    byte[] data = new byte[100];
                    int size = client.Receive(data);
                    Console.WriteLine("Recieved data: ");
                    for (int i = 0; i < size; i++)
                        Console.Write(Convert.ToChar(data[i]));

                    //respond to client


                    Console.WriteLine("\n");

                    client.Close();

                    Console.WriteLine("Waiting for a connection...");
                });

            childSocketThread.Start();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("Error: " + e.StackTrace);
        Console.ReadLine();
    }
}

如何更改这两个应用程序,以便在服务器收到数据后,以某种确认方式响应客户端?

How can I alter both of these applications so that when the Server has received the data, it responds to the Client with some kind of confirmation?

提前致谢!

推荐答案

这是我将如何做的一个简短示例:

Here a short example how I would do it:

服务器:

class Server
    {
        static void Main(string[] args)
        {
            TcpListener listener = new TcpListener(IPAddress.Any, 1500);
            listener.Start();

            TcpClient client = listener.AcceptTcpClient();

            NetworkStream stream = client.GetStream();

            // Create BinaryWriter for writing to stream
            BinaryWriter binaryWriter = new BinaryWriter(stream);

            // Creating BinaryReader for reading the stream
            BinaryReader binaryReader = new BinaryReader(stream);

            while (true) 
            {
                // Read incoming information
                byte[] data = new byte[16];
                int receivedDataLength = binaryReader.Read(data, 0, data.Length);
                string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);

                // Write incoming information to console
                Console.WriteLine("Client: " + stringData);

                // Respond to client
                byte[] respondData = Encoding.ASCII.GetBytes("respond");
                Array.Resize(ref respondData, 16); // Resizing to 16 byte, because in this example all messages have 16 byte to make it easier to understand.
                binaryWriter.Write(respondData, 0, 16);
            }

        }
    }

客户:

class Client
    {
        private static void Main(string[] args)
        {
            Console.WriteLine("Press any key to start Client");
            while (! Console.KeyAvailable)
            {
            }


            TcpClient client = new TcpClient();
            client.Connect("127.0.0.1", 1500);

            NetworkStream networkStream = client.GetStream();

            // Create BinaryWriter for writing to stream
            BinaryWriter binaryWriter = new BinaryWriter(networkStream);

            // Creating BinaryReader for reading the stream
            BinaryReader binaryReader = new BinaryReader(networkStream);

            // Writing "test" to stream
            byte[] writeData = Encoding.ASCII.GetBytes("test");
            Array.Resize(ref writeData, 16); // Resizing to 16 byte, because in this example all messages have 16 byte to make it easier to understand.
            binaryWriter.Write(writeData, 0, 16);

            // Reading response and writing it to console
            byte[] responeBytes = new byte[16];
            binaryReader.Read(responeBytes, 0, 16);
            string response = Encoding.ASCII.GetString(responeBytes);
            Console.WriteLine("Server: " + response);


            while (true)
            {
            }
        }
    }

我希望这会有所帮助!;)

I hope this helps! ;)

这篇关于使用套接字响应客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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