C# WPF新手入门之TCP通讯.docx
- 文档编号:8169274
- 上传时间:2023-01-29
- 格式:DOCX
- 页数:13
- 大小:184.18KB
C# WPF新手入门之TCP通讯.docx
《C# WPF新手入门之TCP通讯.docx》由会员分享,可在线阅读,更多相关《C# WPF新手入门之TCP通讯.docx(13页珍藏版)》请在冰豆网上搜索。
C#WPF新手入门之TCP通讯
C#WPF新手入门之TCP通讯
本文包括服务器和客户端两部分,服务器可以监听多个客户端,以及判断哪个客户端处理连接或者断开状态,服务器和客户端可以互发数据。
实际效果如下:
我们可以用TCP测试工具测试:
以下为代码:
服务器端:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Text;
usingSystem.Threading;
usingSystem.Threading.Tasks;
usingSystem.Windows;
usingSystem.Windows.Controls;
usingSystem.Windows.Data;
usingSystem.Windows.Documents;
usingSystem.Windows.Input;
usingSystem.Windows.Media;
usingSystem.Windows.Media.Imaging;
usingSystem.Windows.Navigation;
usingSystem.Windows.Shapes;
namespaceWPF_TCP
{
///
///MainWindow.xaml的交互逻辑
///
///
publicpartialclassMainWindow:
Window
{
SocketsocketSend;
//将连接的客户端IP地址和Socket存入集合中
Dictionary
byte[]testBuffer=Encoding.UTF8.GetBytes("Test");
publicMainWindow()
{
InitializeComponent();
}
privateDateTimeGetCurrentTime()//获取系统时间
{
DateTimecurrentTime=newDateTime();
currentTime=DateTime.Now;
returncurrentTime;
}
privatevoidButton_Click(objectsender,RoutedEventArgse)
{
try
{
//点点击开始监听的时候在服务器端创建一个负责监听IP地址和端口号的Scoket
SocketsocketWatch=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPAddressip=IPAddress.Parse(TextBox1.Text.Trim());//获取文本框IP,去除两端空格
//创建端口号对象
IPEndPointiPEndPoint=newIPEndPoint(ip,Convert.ToInt32(TextBox_Port.Text));
socketWatch.Bind(iPEndPoint);//监听
ShowMessage(GetCurrentTime()+"---"+"开始监听客户端传来到的信息:
");
socketWatch.Listen(10);//监听队列长度限制为10
Threadth1=newThread(Listen)
{
IsBackground=true//该线程为后台线程,将会随着主线程的退出而退出
};
th1.Start(socketWatch);
}
catch(Exception)
{
throw;
}
}
//等待客户端连接并且创建与之通信用的Socket
privatevoidListen(objecto)//被线程执行的方法,如果有参数需是object
{
Socketsocket=oasSocket;
while(true)
{
try
{
//等待客户端连接并且创建一个负责通信的Socket
socketSend=socket.Accept();
Dispatcher.Invoke(newAction(()=>
{
ClientList.Add(socketSend.RemoteEndPoint.ToString(),socketSend);//存到集合
Combox1.Items.Add(socketSend.RemoteEndPoint.ToString());//存到combobox
ShowMessage(GetCurrentTime()+"---"+socketSend.RemoteEndPoint.ToString()+":
"+"连接成功!
");
}),null);
//开启新线程不停接收客户端发送过来的数据
Threadth2=newThread(Receive)
{
IsBackground=true
};
th2.Start(socketSend);
}
catch(Exceptione)
{
Dispatcher.Invoke(newAction(()=>
{
ShowMessage(e.ToString());
}),null);
}
}
}
//服务器端不停接收客户端发过来的消息
privatevoidReceive(objecto)
{
Socketsocket=oasSocket;
while(true)
{
try
{
byte[]buffer=newbyte[1024*1024];
intlength=socket.Receive(buffer);
if(length==0)//断开客户端,结束循环
{
Dispatcher.Invoke(newAction(()=>
{
foreach(variteminCombox1.Items)
{
try
{
Dispatcher.Invoke(newAction(()=>
{
ClientList[item.ToString()].Send(testBuffer);//发送测试数据给客户端判断通讯是否正常
ClientList[item.ToString()].Send(testBuffer);
}),null);
}
catch(Exceptionerr)//判断哪个客户端断开连接
{
Dispatcher.Invoke(newAction(()=>
{
ShowMessage(GetCurrentTime()+"---"+item.ToString()+"断开连接!
");
Combox1.SelectedItem=item;
}),null);
}
}
Combox1.Items.Remove(Combox1.SelectedItem);//移除断开连接的客户端IP
}),null);
break;
}
stringstr=Encoding.UTF8.GetString(buffer,0,length);
Dispatcher.Invoke(newAction(()=>
{
ShowMessage(GetCurrentTime()+"---"+socket.RemoteEndPoint.ToString()+":
"+str);
}),null);
}
catch(Exceptione)//若强制关闭客户端,比如调试程序直接结束
{
foreach(variteminCombox1.Items)
{
try
{
Dispatcher.Invoke(newAction(()=>
{
ClientList[item.ToString()].Send(testBuffer);//同样发送测试数据给客户端判断通讯是否正常ClientList[item.ToString()].Send(testBuffer);
}),null);
}
catch(Exceptionerr)//判断哪个客户端断开连接
{
Dispatcher.Invoke(newAction(()=>
{
ShowMessage(GetCurrentTime()+"---"+item.ToString()+"强制关闭!
");
}),null);
}
}//这里漏了把断开的客户端IP移除combobox…
break;
}
}
}
privatevoidShowMessage(stringstr)//文本框信息提示
{
TextBox2.AppendText(str+"\r\n");
TextBox2.ScrollToEnd();
}
///
///给客户端发送消息
///
///
///
privatevoidSendMsg_Click(objectsender,RoutedEventArgse)
{
stringstr=TextBox3.Text.Trim().ToString();
byte[]buffer=Encoding.UTF8.GetBytes(str);
//获得combobox地址
stringip=Combox1.SelectedItem.ToString();
ClientList[ip].Send(buffer);
}
}
}
客户端:
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Text;
usingSystem.Threading;
usingSystem.Threading.Tasks;
usingSystem.Windows;
usingSystem.Windows.Controls;
usingSystem.Windows.Data;
usingSystem.Windows.Documents;
usingSystem.Windows.Input;
usingSystem.Windows.Media;
usingSystem.Windows.Media.Imaging;
usingSystem.Windows.Navigation;
usingSystem.Windows.Shapes;
namespaceWPF_TCPClient
{
///
///MainWindow.xaml的交互逻辑
///
publicpartialclassMainWindow:
Window
{
SocketsocketSend;
publicMainWindow()
{
InitializeComponent();
}
privateDateTimeGetCurrentTime()//获取系统时间
{
DateTimecurrentTime=newDateTime();
currentTime=DateTime.Now;
returncurrentTime;
}
///
///连接服务器
///
///
///
privatevoidButton_Click(objectsender,RoutedEventArgse)
{
try
{
//创建负责通信的Socket
socketSend=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPAddressip=IPAddress.Parse(TextBox1.Text.Trim());//获取文本框IP,去除两端空格
//获取要连接的服务器IP地址和端口号
IPEndPointiPEndPoint=newIPEndPoint(ip,Convert.ToInt32(TextBox_Port.Text));
socketSend.Connect(iPEndPoint);//连接服务器
ShowMessage(GetCurrentTime()+"---"+"连接成功!
");
Threadth1=newThread(Receive);
th1.IsBackground=true;
th1.Start();
}
catch//不处理异常,比如服务器未开点击连接服务器卡死问题...
{
}
}
///
///客户端接收服务器消息
///
privatevoidReceive()
{
while(true)
{
try
{
byte[]buffer=newbyte[1024*1024];
intlength=socketSend.Receive(buffer);
if(length==0)
{
break;
}
stringstr=Encoding.UTF8.GetString(buffer,0,length);
Dispatcher.Invoke(newAction(()=>
{
ShowMessage(GetCurrentTime()+"---"+socketSend.RemoteEndPoint.ToString()+":
"+str);
}),null);
}
catch
{
}
}
}
privatevoidShowMessage(stringstr)
{
TextBox2.AppendText(str+"\r\n");
TextBox2.ScrollToEnd();
}
privatevoidSendMsg_Click(objectsender,RoutedEventArgse)//给服务器发送消息
{
stringstr=TextBox3.Text.Trim();//获取文本框内容,去除两端空格
byte[]buffer=Encoding.UTF8.GetBytes(str);
socketSend.Send(buffer);
}
}
}
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- C# WPF新手入门之TCP通讯 WPF 新手入门 TCP 通讯