当前位置:编程学习 > JSP >>

Socket编程项目之后经验谈

我们的项目是用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;
补充:Jsp教程,面向对象编程
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,