实 验 报 告18p.docx
《实 验 报 告18p.docx》由会员分享,可在线阅读,更多相关《实 验 报 告18p.docx(20页珍藏版)》请在冰点文库上搜索。
实验报告18p
实验报告
学院(部):
理学院班级:
信计1101班学号:
姓名:
杨宠
实验课程
C#程序设计
实验名称
利用同步TCP编写网络聊天程序
指导老师
江力
实验性质
(选修、必修)
必修
实验类型
(验证、设计、创新、综合)
验证
实验课时
4课时
实验日期、时间
2013-9-18
2013-10-09
实验消耗材料
PC机
实验仪器设备
(实验硬件要求)
计算机一台,Visualstadio2010
实验目的
掌握C#的同步TCP应用编程方法。
实验内容(实验原理、可用的理论知识、算法、程序、步骤和方法)
一、实验内容
同步TCP服务器端应用编程与客户端应用编程。
二、实验基本原理
利用TcpListener类、TcpClient类、Socket类提供的方法进行同步TCP应用编程。
三、注意事项
BinaryReader,BinaryWriter类的应用,及TCP类及协议的一些知识运用。
四、实验步骤
1、同步TCP服务器端应用编程:
网络聊天服务器;
2、同步TCP客户端应用编程:
网络聊天客户端。
1.服务器端编程:
(1)创建一个名为SyncChatServer的Windows应用程序,将Form1.cs换名为MainForm.cs,设计界面如下图所示:
(2)在解决方案资源管理器中,添加一个名为User.cs的文件,用于保存与客户通信需要的信息,代码如下:
using
usingSystem.IO;
namespaceSyncChatServer
{
classUser
{
publicTcpClientclient;//{get;privateset;}
publicBinaryReaderbr;//{get;privateset;}
publicBinaryWriterbw;//{get;privateset;}
publicstringuserName;//{get;set;}
publicUser(TcpClientclient)
{
this.client=client;
NetworkStreamnetworkStream=client.GetStream();
br=newBinaryReader(networkStream);
bw=newBinaryWriter(networkStream);
}
publicvoidClose()
{
br.Close();
bw.Close();
client.Close();
}
}
}
(3)在MainForm中添加对应的代码和事件:
usingSystem;
using
using
//添加的命名空间引用
usingSystem.Net;
using
usingSystem.Threading;
namespaceSyncChatServer
{
publicpartialclassMainForm:
Form
{
///保存连接的所有用户
privateListuserList=newList();
///使用的本机IP地址
IPAddresslocalAddress;
///监听端口
privateconstintport=51888;
privateTcpListenermyListener;
///是否正常退出所有接收线程
boolisNormalExit=false;
publicMainForm()
{
InitializeComponent();
listBoxStatus.HorizontalScrollbar=true;
IPAddress[]addrIP=Dns.GetHostAddresses(Dns.GetHostName());
localAddress=addrIP[0];
buttonStop.Enabled=false;
}
///【开始监听】按钮的Click事件
privatevoidbuttonStart_Click(objectsender,EventArgse)
{
myListener=newTcpListener(localAddress,port);
myListener.Start();
AddItemToListBox(string.Format("开始在{0}:
{1}监听客户连接",localAddress,port));
//创建一个线程监听客户端连接请求
ThreadmyThread=newThread(ListenClientConnect);
myThread.Start();
buttonStart.Enabled=false;
buttonStop.Enabled=true;
}
///接收客户端连接
privatevoidListenClientConnect()
{
TcpClientnewClient=null;
while(true)
{
try
{
newClient=myListener.AcceptTcpClient();
}
catch
{
//当单击“停止监听”或者退出此窗体时AcceptTcpClient()会产生异常
//因此可以利用此异常退出循环
break;
}
//每接受一个客户端连接,就创建一个对应的线程循环接收该客户端发来的信息
Useruser=newUser(newClient);
ThreadthreadReceive=newThread(ReceiveData);
threadReceive.Start(user);
userList.Add(user);
AddItemToListBox(string.Format("[{0}]进入"
AddItemToListBox(string.Format("当前连接用户数:
{0}",userList.Count));
}
}
///
///处理接收的客户端数据
///
///客户端信息
privatevoidReceiveData(objectuserState)
{
Useruser=(User)userState;
TcpClientclient=user.client;
while(isNormalExit==false)
{
stringreceiveString=null;
try
{
//从网络流中读出字符串,此方法会自动判断字符串长度前缀,并根据长度前缀读出字符串
}
catch
{
if(isNormalExit==false)
{
AddItemToListBox(string.Format("与[{0}]失去联系,已终止接收该用户信息"
RemoveUser(user);
}
break;
}
AddItemToListBox(string.Format("来自[{0}]:
{1}"
string[]splitString=receiveString.Split(',');
switch(splitString[0])
{
case"Login":
user.userName=splitString[1];
SendToAllClient(user,receiveString);
break;
case"Logout":
SendToAllClient(user,receiveString);
RemoveUser(user);
return;
case"Talk":
stringtalkString=receiveString.Substring(splitString[0].Length+splitString[1].Length+2);
AddItemToListBox(string.Format("{0}对{1}说:
{2}",
user.userName,splitString[1],talkString));
SendToClient(user,"talk,"+user.userName+","+talkString);
foreach(UsertargetinuserList)
{
if(target.userName==splitString[1]&&user.userName!
=splitString[1])
{
SendToClient(target,"talk,"+user.userName+","+talkString);
break;
}
}
break;
default:
AddItemToListBox("什么意思啊:
"+receiveString);
break;
}
}
}
///
///发送message给user
///
///指定发给哪个用户
///信息内容
privatevoidSendToClient(Useruser,stringmessage)
{
try
{
//将字符串写入网络流,此方法会自动附加字符串长度前缀
AddItemToListBox(string.Format("向[{0}]发送:
{1}",
user.userName,message));
}
catch
{
AddItemToListBox(string.Format("向[{0}]发送信息失败",
user.userName));
}
}
///发送信息给所有客户
///指定发给哪个用户
///信息内容
privatevoidSendToAllClient(Useruser,stringmessage)
{
stringcommand=message.Split(',')[0].ToLower();
if(command=="login")
{
for(inti=0;i{
SendToClient(userList[i],message);
if(userList[i].userName!
=user.userName)
{
SendToClient(user,"login,"+userList[i].userName);
}
}
}
elseif(command=="logout")
{
for(inti=0;i{
if(userList[i].userName!
=user.userName)
{
SendToClient(userList[i],message);
}
}
}
}
///移除用户
///指定要删除的用户
privatevoidRemoveUser(Useruser)
{
userList.Remove(user);
user.Close();
AddItemToListBox(string.Format("当前连接用户数:
{0}",userList.Count));
}
privatedelegatevoidAddItemToListBoxDelegate(stringstr);
///在ListBox中追加状态信息
///要追加的信息
privatevoidAddItemToListBox(stringstr)
{
if(listBoxStatus.InvokeRequired)
{
AddItemToListBoxDelegated=AddItemToListBox;
listBoxStatus.Invoke(d,str);
}
else
{
listBoxStatus.ClearSelected();
}
}
///【停止监听】按钮的Click事件
privatevoidbuttonStop_Click(objectsender,EventArgse)
{
AddItemToListBox("开始停止服务,并依次使用户退出!
");
isNormalExit=true;
for(inti=userList.Count-1;i>=0;i--)
{
RemoveUser(userList[i]);
}
//通过停止监听让myListener.AcceptTcpClient()产生异常退出监听线程
myListener.Stop();
buttonStart.Enabled=true;
buttonStop.Enabled=false;
}
///关闭窗口时触发的事件
privatevoidMainForm_FormClosing(objectsender,FormClosingEventArgse)
{
if(myListener!
=null)
{
//引发buttonStop的Click事件
buttonStop.PerformClick();
}
}
}
}
2.客户端编程:
(1)创建一个名为SyncChatClient的Windows应用程序,将Form1.cs换名为MainForm.cs,
(2)在MainForm中添加对应的代码和事件,源程序如下:
usingSystem;
using
//添加的命名空间引用
usingSystem.Net;
using
usingSystem.Threading;
usingSystem.IO;
namespaceSyncChatClient
{
publicpartialclassMainForm:
Form
{
privateboolisExit=false;
privateTcpClientclient;
privateBinaryReaderbr;
privateBinaryWriterbw;
publicMainForm()
{
InitializeComponent();
Randomr=newRandom((int)DateTime.Now.Ticks);
textBoxUserName.Text="user"+r.Next(100,999);
listBoxOnlineStatus.HorizontalScrollbar=true;
}
///
///【连接服务器】按钮的Click事件
///
privatevoidbuttonConnect_Click(objectsender,EventArgse)
{
buttonConnect.Enabled=false;
try
{
//此处为方便演示,实际使用时要将Dns.GetHostName()改为服务器域名
client=newTcpClient(Dns.GetHostName(),51888);
AddTalkMessage("连接成功");
}
catch
{
AddTalkMessage("连接失败");
buttonConnect.Enabled=true;
return;
}
//获取网络流
NetworkStreamnetworkStream=client.GetStream();
//将网络流作为二进制读写对象
br=newBinaryReader(networkStream);
bw=newBinaryWriter(networkStream);
SendMessage("Login,"+textBoxUserName.Text);
ThreadthreadReceive=newThread(newThreadStart(ReceiveData));
threadReceive.IsBackground=true;
threadReceive.Start();
}
///处理接收的服务器端数据
privatevoidReceiveData()
{
stringreceiveString=null;
while(isExit==false)
{
try
{
//从网络流中读出字符串
//此方法会自动判断字符串长度前缀,并根据长度前缀读出字符串
receiveString=br.ReadString();
}
catch
{
if(isExit==false)
{
MessageBox.Show("与服务器失去联系。
");
}
break;
}
string[]splitString=receiveString.Split(',');
stringcommand=splitString[0].ToLower();
switch(command)
{
case"login":
//格式:
login,用户名
AddOnline(splitString[1]);
break;
case"logout":
//格式:
logout,用户名
RemoveUserName(splitString[1]);
break;
case"talk":
//格式:
talk,用户名,对话信息
//AddTalkMessage(splitString[1]+":
\r\n");
//AddTalkMessage(receiveString.Substring(
//splitString[0].Length+splitString[1].Length+2));
AddTalkMessage(string.Format("[{0}]说:
{1}",
splitString[1],receiveString.Substring(
splitString[0].Length+splitString[1].Length+2)));
break;
default:
AddTalkMessage("什么意思啊:
"+receiveString);
break;
}
}
Application.Exit();
}
///向服务器端发送信息
privatevoidSendMessage(stringmessage)
{
try
{
//将字符串写入网络流,此方法会自动附加字符串长度前缀
bw.Write(message);
bw.Flush();
}
catch
{
AddTalkMessage("发送失败!
");
}
}
///【发送】按钮的Click事件
privatevoidbuttonSend_Click(objectsender,EventArgse)
{
if(listBoxOnlineStatus.SelectedIndex!
=-1)
{
SendMessage("Talk,"+listBoxOnlineStatus.SelectedItem+","+textBoxSend.Text+"\r\n");
//SendMessage("Talk,"+listBoxOnlineStatus.SelectedItem+","+textBoxSend.Text);
textBoxSend.Clear();
}
else
{
MessageBox.Show("请先在[当前在线]中选择一个对话者");
}
}
///关闭窗口时触发的事件
privatevoidMainForm_FormClosing(objectsender,FormClosingEventArgse)
{
//未与服务器连接前client为null
if(client!
=null)
{
SendMessage("Logout,"+textBoxUserName.Text);
isExit=true;
br.Close();
bw.Close();
client.Close();
}
}
///在发送信息文本框中按下【Enter】键触发的事件
privatevoidtextBoxSend_KeyPress(objectsender,KeyPressEventArgse)
{
if(e.KeyChar==(char)Keys.Return)
{
//触发buttonSend的Click事件
buttonSend.PerformClick();
}
}
privatedelegatevoidMessageDelegate(stringmess