0

好的,所以我一般不太擅长编程,但我想尝试使用套接字。首先,我观看了一个逐步遵循的 Youtube 视频,我让最终产品 100% 符合指南,但我希望对其进行修改,以便服务器能够向所有连接的客户端发送消息。

这是 youtube 视频:Youtube 视频 - 套接字

所以这是服务器类的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;

namespace Server
{
    class Program
    {
        private static byte[] buffer = new byte[1024];
        public static Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        public static List<Socket> clientSockets = new List<Socket>();
        static void Main(string[] args)
        {
            Console.Title = "Server, " + clientSockets.Count.ToString() + " clients are connected";
            SetupServer();
            Console.ReadLine();

        }

        public static void SetupServer()
        {

            Console.WriteLine("Setting up server...");
            _serverSocket.Bind(new IPEndPoint(IPAddress.Any, 100));
            _serverSocket.Listen(5);
            _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);

        }

        public static void AcceptCallback(IAsyncResult AR)
        {
            Socket socket = _serverSocket.EndAccept(AR);
            clientSockets.Add(socket);
            Console.WriteLine("Client Connected");
            Console.Title = "Server, " + clientSockets.Count.ToString() + " clients are connected";
            socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallBack), socket);
            _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
        }

        private static void RecieveCallBack(IAsyncResult AR)
        {
            Socket socket = (Socket)AR.AsyncState;
            int received = socket.EndReceive(AR);
            byte[] databuff = new byte[received];
            Array.Copy(buffer, databuff, received);

            string s = Encoding.ASCII.GetString(databuff);
            Console.WriteLine("Text Received: " + s);
            string response = string.Empty;
            if (s.ToLower() == "get time")
            {
                response = DateTime.Now.ToLongTimeString();
            }
            else
            {
                response = "Invalid Request";
            }

            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(RecieveCallBack), socket);
            }




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

我对自己想做的事情进行了一次非常可悲的尝试:

private static void RecieveCallBack(IAsyncResult AR)
        {
            Socket socket = (Socket)AR.AsyncState;
            int received = socket.EndReceive(AR);
            byte[] databuff = new byte[received];
            Array.Copy(buffer, databuff, received);

            string s = Encoding.ASCII.GetString(databuff);
            Console.WriteLine("Text Received: " + s);
            foreach(Socket s1 in clientSockets){
            string response = string.Empty;
            if (s.ToLower() == "get time")
            {
                response = DateTime.Now.ToLongTimeString();
            }
            else
            {
                response = "Invalid Request";
            }

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

并没有真正期待它太有效,但我试了一下。

另一个次要问题:

这是决定服务器将侦听的 IP 和端口的代码行吗?

_serverSocket.Bind(new IPEndPoint(IPAddress.Any, 100));
4

2 回答 2

0

使用相同的代码,遇到了同样的问题。

它不起作用,因为客户端控制台卡在 中readLine(),因此没有收到响应。发送命令后不要再调用Console.ReadLine

要遍历所有客户端并发送消息:

private static void sentToAll(string s)
{
    foreach (Socket socket in clientSockets)
    {                
        byte[] data = Encoding.ASCII.GetBytes(s);
        socket.Send(data);
    }
}
于 2017-09-03T21:45:04.383 回答
-1
     private static IPEndPoint localEndPoint;
    public static String IpAddress = "10.0.0.13";
 public static int port = 3000;
    localEndPoint = new IPEndPoint(IPAddress.Parse(IpAddress), port);
                _serverSocket.Bind(localEndPoint);
于 2017-05-18T17:20:56.707 回答