C#套接字并将数据发送到所有客户端

时间:2013-10-16 03:28:46

标签: c# sockets

好的,所以我不太擅长编程,但我想尝试使用套接字。首先,我看了一个Youtube视频,我一步一步地跟着,我把完成的产品100%运行到指南,但是我想修改它,以便服务器能够向所有连接的客户端发送消息。

以下是YouTube视频:Youtube Video - Sockets

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

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

它无效,因为客户端控制台卡在readLine()中,因此它没有收到响应。发送命令后,请勿再次呼叫Console.ReadLine

循环播放所有客户端并发送消息:

private static void sentToAll(string s)
{
    foreach (Socket socket in clientSockets)
    {                
        byte[] data = Encoding.ASCII.GetBytes(s);
        socket.Send(data);
    }
}