C# 套接字并将数据发送到所有客户端
本文关键字:客户端 套接字 数据 | 更新日期: 2023-09-27 18:35:27
好的,所以我一般不太擅长编程,但我想尝试使用套接字。首先,我观看了一个 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));
使用相同的
代码,遇到相同的问题。
它不起作用,因为客户端控制台卡在 readLine()
中,因此它没有收到响应。发送命令后,不要再次调用Console.ReadLine
。
要遍历所有客户端并发送消息,请执行以下操作:
private static void sentToAll(string s)
{
foreach (Socket socket in clientSockets)
{
byte[] data = Encoding.ASCII.GetBytes(s);
socket.Send(data);
}
}
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);