C#面向连接的TCP同步通信.docx
- 文档编号:2660169
- 上传时间:2023-05-04
- 格式:DOCX
- 页数:20
- 大小:39.10KB
C#面向连接的TCP同步通信.docx
《C#面向连接的TCP同步通信.docx》由会员分享,可在线阅读,更多相关《C#面向连接的TCP同步通信.docx(20页珍藏版)》请在冰点文库上搜索。
C#面向连接的TCP同步通信
本程序的执行界面如下:
创建通信程序界面需要:
一个名为textBox_user的TextBox,一个名为textBox_accept的TextBox,一个名为textBox_send的TextBox。
四个按钮的属性如下:
监听:
btn_login
连接远程:
btn_link
发送:
btn_send
关闭:
btn_close
本程序需要同时在两个能够正常通信的电脑上同时开启才能正常使用。
不分主机和客户端(最好选择局域网测试)。
如果在一台电脑上测试:
只需将程序复制两份,同时打开。
当两份程序的portListen和portLink值必须互换,
即一个为
privateintportListen=10000;
privateintportLink=8000;
另一个为:
privateintportListen=8000;
privateintportLink=10000;
然后同时运行。
操作使用方法如下:
1、程序启动后首先点击“监听”按钮(两个客户端均要执行该操作),
然后在“对方IP”文本框中输入一个要连接的对方IP(如果是本机,则输入本机IP,本机IP已在聊天信息文本框中显示)。
2、输入完毕后点击“连接远程”按钮,程序会提示连接成功与否,如果连接成功,界面如下图
3、此时在“发送信息”文本框中,点击“发送”按钮,便可以进行正常通信。
4、通信结束后,点击“关闭”按钮,程序再次进入监听状态,可以接受其他客户端的链接请求。
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Net.Sockets;
usingSystem.Net;
usingSystem.Threading;
namespaceTCPconn
{
publicpartialclassForm1:
Form
{
#region字段
privateIPAddressHostIp,RemoteIP;
privateintportListen=10000;
privateintportLink=8000;
privateIPEndPointendPoint;
privateSocketsocket=null;
privateSocketacceptSocket=null;
privateSocketsendSocket=null;
ThreadthreadListen=null;
ThreadthreadSend=null;
privateintlen=0;//接收字节数
#endregion字段
#region构造函数
publicForm1()
{
InitializeComponent();
IPHostEntryhost=Dns.GetHostEntry(Dns.GetHostName());
foreach(IPAddressipinhost.AddressList)
{
if(!
ip.IsIPv6LinkLocal)
{
textBox_accept.AppendText("本机IP地址:
"+ip.ToString()+"\n");
HostIp=ip;
}
}
endPoint=newIPEndPoint(HostIp,portListen);
}
#endregion构造函数
#region委托
///
///在接收文本框中附加信息
///
///
delegatevoidSetTextCallback(stringstr);
//执行函数
privatevoidsetText(stringstr)
{
textBox_accept.AppendText(str);
textBox_accept.AppendText("\n");
}
///
///设置“连接按钮”可用性
///
///
delegatevoidSetBtnEnableHandler(boolstate);
//执行函数
privatevoidsetEnable(boolstate)
{
btn_link.Enabled=state;
}
#endregion委托
#region自定义函数
///
///打开端口监听
///
privatevoidopenListener()
{
this.Invoke(newSetTextCallback(setText),newobject[]{"已经开启监听!
"});
try
{
socket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
socket.Bind(endPoint);
socket.Listen(0);
//acceptSocket=socket.Accept();
if(threadListen!
=null)
{
try
{
threadListen.Abort();
}
catch(Exception){}
threadListen=null;
}
threadListen=newThread(newThreadStart(Proccess1));
threadListen.Start();
}
catch(Exceptionex)
{
MessageBox.Show(ex.Message);
}
}
///
///发送信息
///
///
privatevoidsendMessage(stringmsg)
{
try
{
byte[]sendByte=newbyte[msg.Length];
sendByte=Encoding.Unicode.GetBytes(msg.ToCharArray());
try
{
if(acceptSocket!
=null)
{
if(acceptSocket.Connected)
{
//textBox_accept.AppendText(acceptSocket.RemoteEndPoint.ToString()+"\n");
acceptSocket.Send(sendByte,sendByte.Length,0);
}
}
elseif(sendSocket!
=null)
{
if(sendSocket.Connected)
{
//textBox_accept.AppendText(sendSocket.RemoteEndPoint.ToString()+"\n");
sendSocket.Send(sendByte,sendByte.Length,0);
}
}
}
catch(Exceptionex)
{
MessageBox.Show(ex.Message);
}
}
catch(Exceptionex)
{
MessageBox.Show("发送失败:
"+ex.Message);
}
}
///
///链接远程客户端
///
///
privatevoidremoteLink(IPAddressremoteIP)
{
try
{
//如果此时监听线程仍在工作,则关闭监听线程
try
{
if(threadListen!
=null)
{
threadListen.Abort();
threadListen=null;
}
}
catch(Exception){}
if(socket!
=null)
{
try
{
socket.Close();
}
catch(Exception){}
finally
{
socket=null;
}
}
if(acceptSocket!
=null)
{
try
{
acceptSocket.Close();
}
catch(Exception){}
finally
{
acceptSocket=null;
}
}
//远程端口
IPEndPointremotePoint=newIPEndPoint(remoteIP,portLink);
sendSocket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
sendSocket.Connect(remotePoint);
if(threadSend!
=null)
{
try
{
threadSend.Abort();
}
catch(Exception){}
threadSend=null;
}
threadSend=newThread(newThreadStart(sendProc1));
threadSend.Start();
btn_link.Enabled=false;
try
{
stringsendStr="已经与"+this.textBox_user.Text.Trim()+"建立连接";
byte[]sendByte=newbyte[sendStr.Length];
sendByte=Encoding.Unicode.GetBytes(sendStr.ToCharArray());
sendSocket.Send(sendByte,sendByte.Length,0);
}
catch(Exceptionex)
{
MessageBox.Show("发送失败:
"+ex.Message);
}
}
catch(Exceptionex)
{
btn_link.Enabled=true;
MessageBox.Show("服务器没有开启\r\n"+ex.Message);
}
}
///
///主监听进程
///
privatevoidProccess1()
{
while(true)
{
try
{
if(acceptSocket==null)
{
acceptSocket=socket.Accept();
}
else
{
byte[]recBytes=newbyte[512];
len=acceptSocket.Receive(recBytes,recBytes.Length,0);
stringstrInfo=Encoding.Unicode.GetString(recBytes,0,len);
if(len>=3)
{
if(strInfo.Substring(0,3)=="已经与")
{
this.Invoke(newSetBtnEnableHandler(setEnable),newobject[]{false});
byte[]sendBytes=newbyte[64];
sendBytes=Encoding.Unicode.GetBytes("对方已接收链接请求,可以开始通信!
".ToCharArray());
acceptSocket.Send(sendBytes,sendBytes.Length,0);
}
if(strInfo=="关闭通信")
{
try
{
acceptSocket.Shutdown(SocketShutdown.Both);
acceptSocket.Close();
strInfo="对方已将通信关闭,重新开始监听!
";
}
catch(Exception){}
finally
{
//关闭当前使用的套接字和进程
acceptSocket=null;
}
this.Invoke(newSetBtnEnableHandler(setEnable),newobject[]{true});
}
}
this.Invoke(newSetTextCallback(setText),newobject[]{strInfo});
}
}
catch(Exception)
{
try
{
threadListen.Abort();
}
catch(Exception){}
//MessageBox.Show(ex.ToString());
//MessageBox.Show("接收失败"+ex.Message);
}
}
}
///
///连接远程主机后的监听进程
///
privatevoidsendProc1()
{
while(true)
{
try
{
byte[]recBytes=newbyte[512];
len=sendSocket.Receive(recBytes);
stringstrInfo=Encoding.Unicode.GetString(recBytes,0,len);
if(len>=3)
{
if(strInfo=="关闭通信")
{
//this.closeSocket();
//强行重新打开监听
this.openListener();
try
{
sendSocket.Shutdown(SocketShutdown.Both);
sendSocket.Close();
strInfo="对方已将通信关闭,重新开始监听!
";
}
catch(Exception){}
finally
{
//关闭当前使用的套接字
sendSocket=null;
}
this.Invoke(newSetBtnEnableHandler(setEnable),newobject[]{true});
}
}
this.Invoke(newSetTextCallback(setText),newobject[]{strInfo});
}
catch(Exception)
{
try
{
threadSend.Abort();
}
catch(Exception){}
//MessageBox.Show(ex.ToString());
//MessageBox.Show("接收失败\n"+ex.Message);
}
}
}
///
///关闭套接字
///
privatevoidcloseSocket()
{
if(socket!
=null)//关闭主监听套接字
{
try
{
socket.Close();
}
catch(Exception){}
finally
{
socket=null;
}
}
if(acceptSocket!
=null)//关闭接收数据套接字
{
try
{
acceptSocket.Close();
}
catch(Exception){}
finally
{
acceptSocket=null;
}
}
if(sendSocket!
=null)//关闭用于接收远程连接数据的套接字
{
try
{
sendSocket.Close();
}
catch(Exception){}
finally
{
sendSocket=null;
}
}
}
///
///关闭所有的进程
///
privatevoidcloseThread()
{
try//尝试关闭sendProc线程
{
if(threadListen!
=null)
{
threadListen.Abort();
threadListen=null;
}
}
catch(Exception){}
try//尝试关闭Proccess线程
{
if(threadSend!
=null)
{
threadSend.Abort();
threadSend=null;
}
}
catch(Exception){}
}
#endregion自定义函数
///
///开启主监听进程
///
///
///
privatevoidbtn_login_Click(objectsender,EventArgse)
{
textBox_user.Text="";
this.openListener();
}
///
///点击发送按钮
///
///
///
privatevoidbtn_send_Click(objectsender,EventArgse)
{
stringsendStr=HostIp.ToString()+":
"+textBox_send.Text;
textBox_accept.AppendText("本机:
"+textBox_send.Text+"\n");
this.sendMessage(sendStr);
}
///
///关闭通信程序
///
///
///
privatevoidbtn_close_Click(objectsender,EventArgse)
{
this.sendMessage("关闭通信");
this.closeThread();//关闭进程
this.closeSocket();//关闭套接字
btn_link.Enabled=true;
textBox_accept.AppendText("当前通信连接已经关闭!
\n");
this.openListener();
}
///
///连接远程主机
///
///
///
privatevoidbtn_link_Click(objectsender,EventArgse)
{
if(textBox_user.Text.Trim()=="")
{
return;
}
try
{
RemoteIP=IPAddress.Parse(textBox_user.Text.Trim());
}
catch(Exception)
{
textBox_user.Focus();
textBox_user.SelectAll();
return;
}
this.remoteLink(RemoteIP);
}
privatevoidForm1_FormClosing(objectsender,FormClosingEventArgse)
{
this.closeThread();
this.closeSocket();
}
}
}
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- C# 面向 连接 TCP 同步 通信