网络聊天工具socket编程心得

网络聊天工具socket编程心得

ID:860630

大小:163.03 KB

页数:24页

时间:2017-09-21

网络聊天工具socket编程心得_第1页
网络聊天工具socket编程心得_第2页
网络聊天工具socket编程心得_第3页
网络聊天工具socket编程心得_第4页
网络聊天工具socket编程心得_第5页
资源描述:

《网络聊天工具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

当前文档最多预览五页,下载文档查看全文

此文档下载收益归作者所有

当前文档最多预览五页,下载文档查看全文
温馨提示:
1. 部分包含数学公式或PPT动画的文件,查看预览时可能会显示错乱或异常,文件下载后无此问题,请放心下载。
2. 本文档由用户上传,版权归属用户,天天文库负责整理代发布。如果您对本文档版权有争议请及时联系客服。
3. 下载前请仔细阅读文档内容,确认文档内容符合您的需求后进行下载,若出现内容与标题不符可向本站投诉处理。
4. 下载文档时可能由于网络波动等原因无法下载或下载错误,付费完成后未能成功下载的用户请联系客服处理。