最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
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;
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;
相关文章
- 《无限暖暖》天星之羽获得位置介绍 12-20
- 《流放之路2》重铸台解锁方法介绍 12-20
- 《无限暖暖》瞄准那个亮亮的成就怎么做 12-20
- 《无限暖暖》魔气怪终结者完成方法 12-20
- 《无限暖暖》曙光毛团获得位置介绍 12-20
- 《无限暖暖》日光果获得位置介绍 12-20