一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Socket编程项目之后经验谈

时间:2022-07-02 18:02:35 编辑:袖梨 来源:一聚教程网

我们的项目是用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;

热门栏目