网络聊天工具Scket编程心得.docx
- 文档编号:9204700
- 上传时间:2023-02-03
- 格式:DOCX
- 页数:38
- 大小:23.55KB
网络聊天工具Scket编程心得.docx
《网络聊天工具Scket编程心得.docx》由会员分享,可在线阅读,更多相关《网络聊天工具Scket编程心得.docx(38页珍藏版)》请在冰豆网上搜索。
网络聊天工具Scket编程心得
网络聊天工具Scket编程心得
————————————————————————————————作者:
————————————————————————————————日期:
网络聊天工具Socket编程心得
首先要了解TCP协议通信的流程:
1。
服务器端首先创建服务器套接字
2。
服务器套接字监听一个端口,等待客户端的请求
3。
客户端创建一个客户端套接字
4。
客户端向服务器发送请求
5。
服务器确认与客户端的连接
6。
客户端和服务器利用建立的连接进行通信
7。
通信完毕后,客户端和服务器关闭各自的连接
Socket编程基础:
一。
利用Socket建立服务器程序
1。
创建一个服务器套接字,用IP地址和端口初始化服务器
IPAddressipAddress=IPAddress.Parse("127.0.0.1");
TcpListenerlistener=newTcpListener(ipAddress,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,message.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=System.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;
usingSystem.Drawing;
usingSystem.Collections;
usingSystem.ComponentModel;
usingSystem.Windows.Forms;
usingSystem.Data;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Threading;
namespaceChatServer
{
///
///Form1的摘要说明。
///
publicclassChatServerForm:
System.Windows.Forms.Form
{
///
///必需的设计器变量。
///
privateSystem.ComponentModel.Containercomponents=null;
//Theport
staticintport=1234;
privateTcpListenerlistener;
privateSockettmpSocket;
//Themaximalclientstheservercanhold
staticintMaxNum=100;
privateSystem.Windows.Forms.Labellabel1;
privateSystem.Windows.Forms.Labellabel2;
privateSystem.Windows.Forms.TextBoxtxtHost;
privateSystem.Windows.Forms.TextBoxtxtPort;
privateSystem.Windows.Forms.ButtonbtnStart;
privateSystem.Windows.Forms.ButtonbtnExit;
privateSystem.Windows.Forms.Labellabel3;
privateSystem.Windows.Forms.ComboBoxcmbCurUserList;
privateSystem.Windows.Forms.ListBoxlstInfo;
//Thearrayclientsistosavetheonlineclients
staticArrayListclients=newArrayList();
publicChatServerForm()
{
//
//Windows窗体设计器支持所必需的
//
InitializeComponent();
//
//TODO:
在InitializeComponent调用后添加任何构造函数代码
//
}
///
///清理所有正在使用的资源。
///
protectedoverridevoidDispose(booldisposing)
{
if(disposing)
{
if(components!
=null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#regionWindows窗体设计器生成的代码
///
///设计器支持所需的方法-不要使用代码编辑器修改
///此方法的内容。
///
privatevoidInitializeComponent()
{
this.label1=newSystem.Windows.Forms.Label();
this.label2=newSystem.Windows.Forms.Label();
this.txtHost=newSystem.Windows.Forms.TextBox();
this.txtPort=newSystem.Windows.Forms.TextBox();
this.btnStart=newSystem.Windows.Forms.Button();
this.btnExit=newSystem.Windows.Forms.Button();
this.label3=newSystem.Windows.Forms.Label();
this.cmbCurUserList=newSystem.Windows.Forms.ComboBox();
this.lstInfo=newSystem.Windows.Forms.ListBox();
this.SuspendLayout();
//
//label1
//
this.label1.AutoSize=true;
this.label1.Location=newSystem.Drawing.Point(32,32);
this.label1.Name="label1";
this.label1.Size=newSystem.Drawing.Size(54,17);
this.label1.TabIndex=0;
this.label1.Text="主机号:
";
//
//label2
//
this.label2.AutoSize=true;
this.label2.Location=newSystem.Drawing.Point(32,72);
this.label2.Name="label2";
this.label2.Size=newSystem.Drawing.Size(54,17);
this.label2.TabIndex=1;
this.label2.Text="端口号:
";
//
//txtHost
//
this.txtHost.Location=newSystem.Drawing.Point(96,24);
this.txtHost.Name="txtHost";
this.txtHost.Size=newSystem.Drawing.Size(128,21);
this.txtHost.TabIndex=2;
this.txtHost.Text="";
//
//txtPort
//
this.txtPort.Location=newSystem.Drawing.Point(96,64);
this.txtPort.Name="txtPort";
this.txtPort.Size=newSystem.Drawing.Size(128,21);
this.txtPort.TabIndex=3;
this.txtPort.Text="";
//
//btnStart
//
this.btnStart.Location=newSystem.Drawing.Point(256,24);
this.btnStart.Name="btnStart";
this.btnStart.TabIndex=4;
this.btnStart.Text="启动";
this.btnStart.Click+=newSystem.EventHandler(this.btnStart_Click);
//
//btnExit
//
this.btnExit.Location=newSystem.Drawing.Point(256,64);
this.btnExit.Name="btnExit";
this.btnExit.TabIndex=5;
this.btnExit.Text="退出";
this.btnExit.Click+=newSystem.EventHandler(this.btnExit_Click);
//
//label3
//
this.label3.AutoSize=true;
this.label3.Location=newSystem.Drawing.Point(24,112);
this.label3.Name="label3";
this.label3.Size=newSystem.Drawing.Size(91,17);
this.label3.TabIndex=6;
this.label3.Text="当前在线用户:
";
//
//cmbCurUserList
//
this.cmbCurUserList.Location=newSystem.Drawing.Point(120,112);
this.cmbCurUserList.Name="cmbCurUserList";
this.cmbCurUserList.Size=newSystem.Drawing.Size(136,20);
this.cmbCurUserList.TabIndex=7;
//
//lstInfo
//
this.lstInfo.ItemHeight=12;
this.lstInfo.Location=newSystem.Drawing.Point(0,144);
this.lstInfo.Name="lstInfo";
this.lstInfo.Size=newSystem.Drawing.Size(344,160);
this.lstInfo.TabIndex=8;
//
//ChatServerForm
//
this.AutoScaleBaseSize=newSystem.Drawing.Size(6,14);
this.ClientSize=newSystem.Drawing.Size(344,301);
this.Controls.Add(this.lstInfo);
this.Controls.Add(this.cmbCurUserList);
this.Controls.Add(this.label3);
this.Controls.Add(this.btnExit);
this.Controls.Add(this.btnStart);
this.Controls.Add(this.txtPort);
this.Controls.Add(this.txtHost);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name="ChatServerForm";
this.Text="Form1";
this.Load+=newSystem.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
///
///应用程序的主入口点。
///
[STAThread]
staticvoidMain()
{
Application.Run(newChatServerForm());
}
privatevoidForm1_Load(objectsender,System.EventArgse)
{
this.txtPort.ReadOnly=true;
this.txtPort.Text=port.ToString();
this.txtHost.Text="127.0.0.1";
}
privatevoidbtnStart_Click(objectsender,System.EventArgse)
{
try
{
IPAddressip=IPAddress.Parse(this.txtHost.Text);
listener=newTcpListener(ip,port);//创建服务器套字
listener.Start();//开始监听服务器端口
lstInfo.Items.Add("服务器已经启动,正在监听"+txtHost.Text+":
"+txtPort.Text);
//启动一个新的线程,执行方法StartListen,以便在一个独立的进程中执行确认于客户端连接的操作.
Threadthread=newThread(newThreadStart(this.StartListen));
thread.Start();
btnStart.Enabled=false;
}
catch(Exceptionex)
{
lstInfo.Items.Add(ex.Message);
}
}
privatevoidStartListen()
{
while(true)
{
try
{
//当接受到一个客户端请求时,确认与客户端的连接
Socketsocket=listener.AcceptSocket();
//用tmpSocket保存发出请求的客户端实例
tmpSocket=socket;
if(clients.Count>=MaxNum)
{
tmpSocket.Close();
}
else
{
//启动一个新的线程,执行方法this.ServiceClient,处理用户相应的要求
ThreadclientService=newThread(newThreadStart(this.ServiceClient));
clientService.Start();
}
}
catch(Exceptionex)
{
lstInfo.Items.Add(ex.Message);
}
}
}
privatevoidServiceClient()
{
//定义一个数组,用于接收从客户端发送过来的数据,每次所能接收的数据包的最大长度为1024字节
byte[]buffer=newbyte[1024];
SocketclientSocket=tmpSocket;
boolkeepConnect=true;
//用循环不断地与客户端进行交互,直到客户端发出Exit命令,将keepConnect设置为false
//退出循环,关闭连接,中止当前线程
while(keepConnect)
{
//接收数据并存入buffer数组中
clientSocket.Receive(buffer);
//将字符数组转化为字符串
stringclientCommand=System.Text.Encoding.ASCII.GetString(buffer);
string[]tokens=clientCommand.Split('|');
//tokens[0]中保存了命令标识符(CONN或CHAT或PRIV或EXIT)
if(tokens[0]=="CONN")//CONN|用户名|
{
Client_client=newClient(tokens[1],clientSocket);
clients.Add(_client);
lstInfo.Items.Add(tokens[1]+"hasjoined");
//将刚连接的用户名加入到当前在线用户列表中
this.cmbCurUserList.Items.Add(tokens[1]);
//对每一个在线用户发送JOIN和LIST信息命令,以此来更新客户端的在线用户列表
for(inti=0;i { Clientclient=(Client)clients[i]; //向客户端发送JOIN命令,以此来提示有新的客户进入聊天室 SendToClient(client,"JOIN|"+tokens[1]+"|"); Thread.Sleep(100); stringmsgUsers="LIST|"+GetUserList(); //向客户端发送LIST命令,以此来更新客户端的当前在线用户列表 SendToClient(client,msgUsers); } } if(tokens[0]=="CHAT")//CHAT|用户名: 内容| { //向所有当前在线用户转发此信息 for(inti=0;i { Clientclient=(Client)clients[i]; //将"发送者的用户名: 发送内容"转发给用户 SendToClient(client,tokens[1]); } } if(tokens[0]=="PRIV")//PRIV|发送者用户名|接受者用户名|发送内容 { stringsender=tokens[1]; stringreceiver=tokens[2]; stringcontent=tokens[3]; stringmessage=sender+"sendto"+receiver+": "+content; //仅把信息转发给发送者和接收者 for(inti=0;i { Clientclient=(Client)clients[i]; if(client.Name==tokens[2]) { this.SendToClient(client,message); } if(client.Name==tokens[1]) { this.SendToClient(client,message); } } } if(tokens[0]=="EXIT")//EXIT|用户名 { for(inti=0;i { Clientclient=(Client)clients[i]; stringmessage=tokens[1]+"hasgone! "; this.SendToClient(client,message); if(client.Name==tokens[1]) { //将该用户从对应的Client对象从clients数组中删除 clients.RemoveAt(i); //将该用户名从当前在线用户列表中删除 this.cmbCurUserList.Items.Remove(client.Name); //向客户端发送QUIT命令,以此来关闭客户端程序 message
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 网络 聊天工具 Scket 编程 心得