Our project is to use DotNet to implement Socket connection and use multiple threads to process multiple users. Let me talk about the problems encountered in the implementation process. Below is the simplified implementation of my server.
Private Socket clientSocket;
Public void Start ()
{
Thread thread = new Thread (new ThreadStart (MainService ));
Thread. Start ();
}
Void MainService ()
{
Listener = new TcpListener (111111 );
Listener. Start ();
While (true)
{
Socket s = listener. AcceptSocket (); // client connection for frame listening
ClientSocket = s;
Thread clientservice = new Thread (new ThreadStart (ClientService ));
Clientservice. Start ();
Thread. Sleep (200); // 1. Wait for the value to be passed to the variable in the Thread to prevent conflict among multiple users.
}
}
Void ClientService ()
{
String command;
String receiveStr;
String fileName, fileSize;
Socket sock = clientSocket;
EndPoint oldEP = sock. RemoteEndPoint;
Byte [] bb = new byte [2, 200];
While (true)
{
Ii = sock. ReceiveFrom (bb, ref oldEP); // receives data
If (ii = 0) // 2. if the client is disconnected, it will not stop receiving 0 bytes
{
Break;
}
ReceiveStr = Encoding. Default. GetString (bb, 0, bb. Length );
Command = ReadLineFrom (receiveStr, 1). ToLower (); // ReadLineFrom reads a row of data from the string
Switch (command)
{
Cace "upload":
FileName = ReadLineFrom (receiveStr, 2 );
FileSize = ReadLineFrom (receiveStr, 3 );
UploadFile (sock, fileName, Int32.Parse (fileSize); // Method for receiving data,
Break;
....................
}
}
Void uploadFile (Socket sock, string fileName, int fileSize)
{
Int loadSize = 0;
Byte [] bb;