连接带插座的电脑

时间:2016-01-02 13:48:19

标签: c# sockets tcp

我想编写一个程序,其中多个客户端可以在服务器上加入。目前,只要客户端和服务器在同一台PC上,客户端只能询问servertime,它完全正常。我非常确定我必须在客户端的Connect()方法中更改EndPoint,但我不知道应该将其更改为什么。

请帮我找到解决方案。

我的服务器上有这个代码:

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace Multiple_Clients
{
    class Program
    {
        private static int port = 4567;

        private static byte[] _buffer = new byte[1024];
        private static List<Socket> _clientSockets = new List<Socket>();
        private static Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        static void Main(string[] args)
        {
            Console.Title = "Server";
            setupServer();
            Console.ReadLine();
        }

        private static void setupServer()
        {
            Console.WriteLine("Setting up server...");
            _serverSocket.Bind(new IPEndPoint(IPAddress.Any, port));
            _serverSocket.Listen(500);
            _serverSocket.BeginAccept(new AsyncCallback(acceptCallback), null);

        }

        private static void acceptCallback(IAsyncResult AR)
        {
            Socket socket = _serverSocket.EndAccept(AR);
            _clientSockets.Add(socket);
            Console.WriteLine("Client connected");
            socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(receiveCallback), socket);
            _serverSocket.BeginAccept(new AsyncCallback(acceptCallback), null);
        }
        private static void receiveCallback(IAsyncResult AR)
        {
            Socket socket = (Socket)AR.AsyncState;
            int received = socket.EndReceive(AR);
            byte[] dataBuf = new byte[received];
            Array.Copy(_buffer, dataBuf, received);
            string text = Encoding.ASCII.GetString(dataBuf);
            Console.WriteLine("Text received: " + text);

            string response = string.Empty;
            if (text.ToLower() != "get time")
            {
                response = "Invalid Request";
            }
            else
            {
                response = DateTime.Now.ToLongTimeString();
            }

            byte[] data = Encoding.ASCII.GetBytes(response);
            socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(sendCallback), socket);
            socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(receiveCallback), socket);
        }

        private static void sendCallback(IAsyncResult AR)
        {
            Socket socket = (Socket)AR.AsyncState;
            socket.EndSend(AR);
        }
    }
}

这是我的客户

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

namespace Multiple_Clients
{
    class Program
    {
        private static int port = 4567;

        private static Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        static void Main(string[] args)
        {
            Console.Title = "Client";
            connect();
            sendLoop();
            Console.ReadLine();
        }

        private static void connect()
        {
            int attempts = 0;
            while(!_clientSocket.Connected)
            {
                try
                {
                    attempts++;
                    _clientSocket.Connect(IPAddress.Loopback, port);
                }
                catch(SocketException)
                {
                    Console.Clear();
                    Console.WriteLine("Connection attempts: " + attempts.ToString());
                }
            }
            Console.Clear();
            Console.WriteLine("Connected");
        }

        private static void sendLoop()
        {
            while (true)
            {
                Console.Write("Enter a request:");
                string req = Console.ReadLine();
                byte[] buffer = Encoding.ASCII.GetBytes(req);
                _clientSocket.Send(buffer);

                byte[] receivedBuf = new byte[1024];
                int rec = _clientSocket.Receive(receivedBuf);
                byte[] data = new byte[rec];
                Array.Copy(receivedBuf, data, rec);
                Console.WriteLine("Received: " + Encoding.ASCII.GetString(data));
            }
        }
    }
}

欢迎任何有关如何改进此问题的建议。 非常感谢你帮助我!

1 个答案:

答案 0 :(得分:1)

您的客户端始终连接到IPAddress.Loopback ...实际上是本地IP地址127.0.0.1。将IPAddress.Loopback交换到服务器的真实IP地址,例如: G。 IPAddress.Parse(“192.168。?。?”)...!