我正在学习套接字编程,目前遇到了向所有已连接客户端广播消息的困难。
服务器只需使用以下代码启动:
public static int Main(String[] args)
{
Thread t1 = new Thread(Test);
t1.Start();
#region Start listening to socket
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
Console.WriteLine("[{0}] Server started listening!", DateTime.Now);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
#endregion
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
return 0;
}
我在那里启动socket以监听是否有人发送消息。
正如您所看到的,我在上面使用了thread
,我希望该线程不时地向所有已连接的用户发送一些信息(现在只是为了测试而一直发送几个字节)。
这是来自线程的方法:
private static void Test()
{
while (true)
{
for (int i = 0; i < Players.Length; i++)
{
if (Players[i] == null)
continue;
Socket cs = new Socket(Players[i].IPEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
cs.Bind(Players[i].IPEndPoint);
byte[] data = Encoding.ASCII.GetBytes("Random data");
cs.Send(data);
}
}
}
这种方法只是最后的尝试,但并不成功。问题是它给我带来了以下错误:
socket 是 null 的引用。
在这种情况下,但是在任何情况下,我都无法将消息发送给每个客户端。
下面是我如何跟踪客户端连接到服务器的方式。
case "0": // Client tries to connect to server
if (nClients >= MAX_PLAYERS)
{
Send(handler, "Too many players. Try again later.");
return;
}
for (int i = 0; i < MAX_PLAYERS; i++)
{
if(Players[i] == null)
{
Players[i] = new Client();
Players[i].Name = parts[1].ToString();
Players[i].IPEndPoint = handler.RemoteEndPoint as IPEndPoint;
Send(handler, String.Format("1|{0}", i));
Console.WriteLine("[{0}] Succesfully registered client ID: {1}, NAME: {2}!", DateTime.Now, i, parts[1].ToString());
i = MAX_PLAYERS;
nClients++;
}
}
break;
这是我的一个方法中处理连接消息的代码部分:
private static void HandleMessages(string message, Socket handler)
我将其称为“从这里调用”:
public static void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(
state.buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
if (content.IndexOf("<EOF>") > -1)
{
string message = content.Remove(content.Length - 5, 5);
HandleMessages(message, handler);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
}