Experience after Socket programming project

Source: Internet
Author: User

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;

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.