欢迎来到天天文库
浏览记录
ID:860630
大小:163.03 KB
页数:24页
时间:2017-09-21
《网络聊天工具socket编程心得》由会员上传分享,免费在线阅读,更多相关内容在应用文档-天天文库。
1、网络聊天工具Socket编程心得首先要了解TCP协议通信的流程:1。服务器端首先创建服务器套接字2。服务器套接字监听一个端口,等待客户端的请求3。客户端创建一个客户端套接字4。客户端向服务器发送请求5。服务器确认与客户端的连接6。客户端和服务器利用建立的连接进行通信7。通信完毕后,客户端和服务器关闭各自的连接Socket编程基础:一。利用Socket建立服务器程序1。创建一个服务器套接字,用IP地址和端口初始化服务器IPAddressipAddress=IPAddress.Parse("127.0.0.1");TcpListenerlistener=newTcpListener(ipAddr
2、ess,1234);2。监听服务器端口listener.Start();3。确认与客户端的连接Socketsocket=listener.AcceptSocket();4。取得客户端传送过来的信息//将传送过来的信息存入字节数组中byte[]buffer=newbyte[1024];socket.Receive(buffer);5。处理客户端的请求并回应客户端stringmessage="hello";byte[]outbytes=System.Text.Encoding.ASCII.GetBytes(message.ToCharArray());socket.Send(outbytes,m
3、essage.Length,0);6。断开客户端的连接,释放客户端连接socket.Close();7。关闭服务器,释放服务器连接listener.Close();二。利用Socket建立客户端程序1。创建客户端套接字TcpClienttcpClient=newTcpClient();2。连接服务器tcpClient.Connect(IPAddress.Parse("127.0.0.1"),1234);3。得到与服务器通信的流通道NetworkStreamstream=tcpClient.GetStream();4。向服务器发送数据stringcmd="";byte[]outbytes=Sy
4、stem.Text.Encoding.ASCII.GetBytes(cmd.ToCharArray());stream.Write(outbytes,0,outbytes.Length);5。接收从服务器发回的数据byte[]buffer=newbyte[1024];intlen=stream.Read(buffer,0,buffer.Length);stringmsg=System.Text.Encoding.ASCII.GetString(buffer,0,len);6。断开连接tcpClient.Close();服务器端窗体ChatServer.cs:usingSystem;using
5、System.Drawing;usingSystem.Collections;usingSystem.ComponentModel;usingSystem.Windows.Forms;usingSystem.Data;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Threading;namespaceChatServer{//////Form1的摘要说明。///publicclassChatServerForm:System.Windows.Forms.Form{//////必需
6、的设计器变量。///privateSystem.ComponentModel.Containercomponents=null;//Theportstaticintport=1234;privateTcpListenerlistener;privateSockettmpSocket;//ThemaximalclientstheservercanholdstaticintMaxNum=100;privateSystem.Windows.Forms.Labellabel1;privateSystem.Windows.Forms.Labellabel2;privateSyste
7、m.Windows.Forms.TextBoxtxtHost;privateSystem.Windows.Forms.TextBoxtxtPort;privateSystem.Windows.Forms.ButtonbtnStart;privateSystem.Windows.Forms.ButtonbtnExit;privateSystem.Windows.Forms.Labellabel3;private
此文档下载收益归作者所有