我們的項目是用DotNet實現Socket連接,用多線程處理多用戶。我就談一下在實現過程中遇到的問題。下面是我服務器的簡化實現。
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();//幀聽客戶連接
clientSocket=s;
Thread clientservice = new Thread(new ThreadStart(ClientService));
clientservice.Start();
Thread.Sleep(200);//1、等待傳值給線程中的變量,防止多用戶造成沖突
}
}
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);//接收數據
if(ii==0)//2、客戶端連接斷開,就會不停接收0個字節
{
break;
}
receiveStr=Encoding.Default.GetString(bb,0,bb.Length);
command=ReadLineFrom(receiveStr,1).ToLower();//ReadLineFrom讀取字符串中的一行數據
Switch(command)
{
cace “upload“:
fileName=ReadLineFrom(receiveStr,2);
fileSize=ReadLineFrom(receiveStr,3);
uploadFile(sock,fileName,Int32.Parse(fileSize));//接受數據方法,
break;
....................
}
}
void uploadFile(Socket sock,string fileName,int fileSize)
{
int loadSize=0;
byte[] bb;