C#语言编程 服务器端与客户端对话 源程序代码Word文件下载.docx
- 文档编号:21304681
- 上传时间:2023-01-29
- 格式:DOCX
- 页数:19
- 大小:20.02KB
C#语言编程 服务器端与客户端对话 源程序代码Word文件下载.docx
《C#语言编程 服务器端与客户端对话 源程序代码Word文件下载.docx》由会员分享,可在线阅读,更多相关《C#语言编程 服务器端与客户端对话 源程序代码Word文件下载.docx(19页珍藏版)》请在冰豆网上搜索。
publicFormServer()
InitializeComponent();
listBoxStatus.HorizontalScrollbar=true;
IPAddress[]addrIP=Dns.GetHostAddresses(Dns.GetHostName());
//localAddress=addrIP[0];
foreach(varipinaddrIP)
//判断是否为IPv4地址
if(ip.AddressFamily==AddressFamily.InterNetwork)
localAddress=ip;
break;
}
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)
ListenClientDelegated=newListenClientDelegate(ListenClient);
IAsyncResultresult=d.BeginInvoke(outnewClient,null,null);
//使用轮询方式来判断异步操作是否完成
while(result.IsCompleted==false)
if(isExit)
Thread.Sleep(250);
//获取Begin方法的返回值和所有输入/输出参数
d.EndInvoke(outnewClient,result);
if(newClient!
=null)
//每接受一个客户端连接,就创建一个对应的线程循环接收该客户端发来的信息
Useruser=newUser(newClient);
ThreadthreadReceive=newThread(ReceiveData);
threadReceive.Start(user);
userList.Add(user);
[{0}]进入"
newClient.Client.RemoteEndPoint));
当前连接用户数:
{0}"
userList.Count));
else
privatedelegatevoidListenClientDelegate(outTcpClientclient);
接受挂起的客户端连接请求<
privatevoidListenClient(outTcpClientnewClient)
try
newClient=myListener.AcceptTcpClient();
catch
newClient=null;
处理接收的客户端数据<
privatevoidReceiveData(objectuserState)
Useruser=(User)userState;
TcpClientclient=user.client;
while(isExit==false)
stringreceiveString=null;
ReceiveMessageDelegated=newReceiveMessageDelegate(ReceiveMessage);
IAsyncResultresult=d.BeginInvoke(user,outreceiveString,null,null);
d.EndInvoke(outreceiveString,result);
if(receiveString==null)
if(isExit==false)
与[{0}]失去联系,已终止接收该用户信息"
client.Client.RemoteEndPoint));
RemoveUser(user);
来自[{0}]:
{1}"
user.client.Client.RemoteEndPoint,receiveString));
string[]splitString=receiveString.Split('
'
);
switch(splitString[0])
case"
Login"
:
user.userName=splitString[1];
AsyncSendToAllClient(user,receiveString);
Logout"
return;
Talk"
stringtalkString=receiveString.Substring(splitString[0].Length+splitString[1].Length+2);
{0}对{1}说:
{2}"
user.userName,splitString[1],talkString));
AsyncSendToClient(user,"
talk,"
+user.userName+"
"
+talkString);
foreach(UsertargetinuserList)
if(target.userName==splitString[1]&
&
user.userName!
=splitString[1])
AsyncSendToClient(target,"
default:
AddItemToListBox("
什么意思啊:
"
+receiveString);
delegatevoidReceiveMessageDelegate(Useruser,outstringreceiveMessage);
接受客户端发来的信息<
privatevoidReceiveMessage(Useruser,outstringreceiveMessage)
receiveMessage=user.br.ReadString();
catch(Exceptionex)
AddItemToListBox(ex.Message);
receiveMessage=null;
异步发送message给user<
privatevoidAsyncSendToClient(Useruser,stringmessage)
SendToClientDelegated=newSendToClientDelegate(SendToClient);
IAsyncResultresult=d.BeginInvoke(user,message,null,null);
d.EndInvoke(result);
privatedelegatevoidSendToClientDelegate(Useruser,stringmessage);
发送message给user<
privatevoidSendToClient(Useruser,stringmessage)
//将字符串写入网络流,此方法会自动附加字符串长度前缀
user.bw.Write(message);
user.bw.Flush();
向[{0}]发送:
user.userName,message));
向[{0}]发送信息失败"
user.userName));
异步发送信息给所有客户<
privatevoidAsyncSendToAllClient(Useruser,stringmessage)
stringcommand=message.Split('
)[0].ToLower();
if(command=="
login"
)
for(inti=0;
i<
userList.Count;
i++)
AsyncSendToClient(userList[i],message);
if(userList[i].userName!
=user.userName)
login,"
+userList[i].userName);
elseif(command=="
logout"
移除用户<
privatevoidRemoveUser(Useruser)
userList.Remove(user);
user.Close();
privatedelegatevoidAddItemToListBoxDelegate(stringstr);
在ListBox中追加状态信息<
paramname="
str"
>
要追加的信息<
/param>
privatevoidAddItemToListBox(stringstr)
if(listBoxStatus.InvokeRequired)
AddItemToListBoxDelegated=AddItemToListBox;
listBoxStatus.Invoke(d,str);
listBoxStatus.Items.Add(str);
listBoxStatus.SelectedIndex=listBoxStatus.Items.Count-1;
listBoxStatus.ClearSelected();
【停止监听】按钮的Click事件<
privatevoidbuttonStop_Click(objectsender,EventArgse)
开始停止服务,并依次使用户退出!
isExit=true;
for(inti=userList.Count-1;
i>
=0;
i--)
RemoveUser(userList[i]);
//通过停止监听让myListener.AcceptTcpClient()产生异常退出监听线程
myListener.Stop();
buttonStart.Enabled=true;
关闭窗口时触发的事件<
privatevoidMainForm_FormClosing(objectsender,FormClosingEventArgse)
if(myListener!
//引发buttonStop的Click事件
buttonStop.PerformClick();
}
usingSystem.ComponentModel;
usingSystem.IO;
namespaceAsyncTcpClient
publicpartialclassFormClient:
//是否正常退出
privateboolisExit=false;
privateTcpClientclient;
privateBinaryReaderbr;
privateBinaryWriterbw;
//BackgroundWorkerconnectWork=newBackgroundWorker();
publicFormClient()
this.StartPosition=FormStartPosition.CenterScreen;
Randomr=newRandom((int)DateTime.Now.Ticks);
textBoxUserName.Text="
user"
+r.Next(100,999);
listBoxOnline.HorizontalScrollbar=true;
//connectWork.DoWork+=newDoWorkEventHandler(connectWork_DoWork);
//connectWork.RunWorkerCompleted+=
//newRunWorkerCompletedEventHandler(connectWork_RunWorkerCompleted);
//ConnectToServer();
异步方式与服务器进行连接<
voidConnectToServer()
client=newTcpClient();
//此处仅为方便本机调试,实际使用时要将Dns.GetHostName()改为服务器域名
IAsyncResultresult=client.BeginConnect(Dns.GetHostName(),51888,null,null);
Thread.Sleep(100);
AddStatus("
."
client.EndConnect(result);
连接成功"
//获取网络流
NetworkStreamnetworkStream=client.GetStream();
//将网络流作为二进制读写对象
br=newBinaryReader(networkStream);
bw=newBinaryWriter(networkStream);
AsyncSendMessage("
Login,"
+textBoxUserName.Text);
ThreadthreadReceive=newThread(newThreadStart(ReceiveData));
threadReceive.IsBackground=true;
threadReceive.Start();
连接失败:
+ex.Message);
buttonConnect.Enabled=true;
///【连接服务器】按钮的Click事件
privatevoidbuttonConnect_Click(objectsender,EventArgse)
buttonConnect.Enabled=false;
开始连接."
ConnectToServer();
处理接收的服务器端数据<
privatevoidReceiveData()
IAsyncResultresult=d.BeginInvoke(outreceiveString,null,null);
MessageBox.Show("
与服务器失去联系。
stringcommand=splitString[0].ToLower();
switch(command)
//格式:
login,用户名
AddOnline(splitString[1]);
logout,用户名
RemoveUserName(splitString[1]);
talk"
talk,用户名,对话信息
AddTalkMessage(splitString[1]+"
:
\r\n"
AddTalkMessage(receiveString.Substring(
splitString[0].Length+splitString[1].Length+2));
Application.Exit();
///
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- C#语言编程 服务器端与客户端对话 源程序代码 C# 语言 编程 服务器端 客户端 对话 源程序 代码