Analysis of the socket programming in C # (3)

xiaoxiao2021-03-06  41

On the socket programming in C # (3) Author: Wang Kaiming www.ASPCool.com Time: 2002-4-10 21:19:37

The main part of the program should be a serviceclient () function. This function is a stand-alone thread that is the main part of a while loop. In the circulation body, the program handles various client commands. The server receives a string given by the ASCII code from the client, which contains a "|" formal separator. The "|" in the string is the specific command, including four types of CONN, CHAT, PRIV, GONE. The conn command creates a new client connection to send the existing user list to the new user and inform other users to join. The Chat command sends new information to all users. The priv command sends a private message to a user. The Gone command removes an left user from the user list and informs other users to leave. At the same time, the Gone command can set the Boolean variable Keepalive to False to end the threads connected to the client.

The ServiceClient () function is as follows: private void ServiceClient () {Socket client = clientsocket; bool keepalive = true; while (keepalive) {Byte [] buffer = new Byte [1024]; client.Receive (buffer); string clientcommand = System. Text.Encoding.ascii.getstring (buffer); string [] tokens = clientCommand.split (new char [] {'|'}; console.writeLine (ClientCommand); if (tokens [0] == "conn") {For (int N = 0; N {Client Cl = (client) Clients [n]; sendtoclient (cl, "join |" tokens [1]);} endpoint ep = client.remoteEndPoint; Client C = New Client (CLIENT; Tokens [1], EP, ClientService, Client; Clients.Add (c); string message = "list | getChatterlist () " / r / n "; sendtoclient (c, message); lbclients.items.add; lbclients.Ist (c);}} (tokens [0] == "chat") {for (int N = 0; n {Client Cl = (Client) Clients [N]; SendToClient (Cl, ClientCommand);}}}}}} (tokens [0] == "Priv") {string destclient = tokens [3]; for (int N = 0; n {Client Cl = (Client) Clients [n]; if (cl.name.compareto (tokens [3]) == 0) SendToClient (cl, clientcommand); if (cl.name.compareto (tokens [1]) == 0) Sendtoclient (Cl, ClientCommand);}}} (tokens [0] == "gone") {int Remove = 0; BOOL FOUND = FALSE

转载请注明原文地址:https://www.9cbs.com/read-72643.html

New Post(0)