socket编程open in new window

posted on 2004-09-14 19:01 I have I can 阅读(814)

socket在我平时的项目中好象从来都没用过,不过一般的聊天小程序都是用它来完成的。

常规做法:

socket.connect                   //连接
socket.send()                    //发送

接收端:

IPHostEntry entry=new IPHostEntry();
entry=Dns.Resolve(Dns.GetHostName());   //得到本机的机器名并解析
IPAddress[] address=new IPAddress[1];
address=entry.AddressList;
IPEndPoint point=new IPEndPoint(address[0],2000);       //得到本机的ip和选择端口
socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.IP);
socket.Bind(point);                   //socket绑定端口
while(true)
{
    socket.Listen(100);                   //监听
    Socket t=socket.Accept();             //接受
    t.Receive(b);                         //接收数据,存入byte[] b
}
Contributors: FHL