Our project is to use dotnet to implement socket connection, with multithreading to deal with multiple users. I'll just talk about the problems I encountered during the implementation process. Here is a 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 ()//frame listening to customer connection
Clientsocket=s;
Thread clientservice = new Thread (new ThreadStart (ClientService));
ClientService. Start ();
Thread.Sleep (200);//1, wait to pass the value to the variable in the thread, prevent multiple users from causing conflict
}
}
void ClientService ()
{
string command;
String Receivestr;
String filename,filesize;
Socket Sock=clientsocket;
EndPoint Oldep=sock. Remoteendpoint;
Byte[] Bb=new byte[200];
while (true)
{
Ii=sock. ReceiveFrom (Bb,ref OLDEP);//Receive Data
if (ii==0)//2, client connection is disconnected, it will receive 0 bytes continuously
{
Break
}
Receivestr=encoding.default.getstring (BB,0,BB. Length);
Command=readlinefrom (receivestr,1). ToLower ();//readlinefrom read one row of data in a string
Switch (command)
{
Cace "Upload":
Filename=readlinefrom (receivestr,2);
Filesize=readlinefrom (receivestr,3);
UploadFile (Sock,filename,int32.parse (fileSize));//Accept data method,
Break
....................
}
}
void UploadFile (Socket sock,string filename,int fileSize)
{
int loadsize=0;
Byte[] BB;
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