socket笔记

来源:互联网 发布:大数据课程视频教程 编辑:程序博客网 时间:2024/05/22 04:41

定义:网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket。端口+Ip地址

服务端通信步骤:

1、服务端建立负责监听ip和端口号的Socket SocketWatch= new Socket(AdressFamlily.InterNetWork,SocketType.Stream,Protocol.Tcp)

IpAdress=IpAdress.Any;IpEndPoint point=new IpEndPoint(IpAdress,Port); 

2、绑定监听端口:SocketWatch.Bind(point);SocketWatch.Listen(point);

3、设置监听队列:排队大小,等待客户端连接。( Socket socketSend= socketWatch.Accpet())

4、建立一个负责通信的Socket(需要开新线程监听) th=new Thread(Listen);th.start(SocketWatch)

Void Listen(Objet o){ Socket socketWatch=o as socket; while(true){socketSend=socketWatch.Accpet()}   }

5、服务端接受数据:int r=socketSend.Receive(buffer=new byte[1024*1024*2])

需要不断接受:while(true){th=new thread(Receive);th.IsBackGround=True;th.start(socketSend)}

接受方法:Receive(o){while(true){socketsend....} }

注:网络中会出现各种异常,这里可以使用try..catch..来隐藏异常,只为不让用户看到。

客户端通信步骤:和服务端类似。服务端发送消息,需要将客户端socket存起来,DicTionary(IpString,Socket)

接发不同类型消息需要在发送的buffer第一位加标记为、使用List<Byte>,list.add(0);list.addRange(buffer) newBuffer=list.toArray()

发送文件:FsRead=new FileStream(path,...);r=FsRead.Read(buffer,0,buffer.lenth);dicSocket[..].send(buffer,0,lenth)

接受文件:sfd = new SaveFileDialog();sfd.showDialog(this);fsWrite.Write(buffer,1,r+1)

震动:for(i<1000) {this.location=new point(100,200);this.location=new point(200,300);}





0 0