博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#学习笔记——TCP通讯
阅读量:5823 次
发布时间:2019-06-18

本文共 5187 字,大约阅读时间需要 17 分钟。

服务端:TcpListener

客户端:TcpClient、NetworkStream

(要熟悉的类,请参照MSDN。)


TCP客户端:

界面:

代码:

 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//引入命名空间
using System.Net;
using System.Net.Sockets;
using System.Threading;
 
namespace CSharp_003_同步TCP客户端
{
public partial class frmMain : Form
{
//定义回调//定义委托
private delegate void ShowReceiveMsgCallBack(string text);
//声明回调//声明委托
private ShowReceiveMsgCallBack showReceiveMsgCallBack;
//定义回调
private delegate void SetProgressBarValueCallBack();
//声明回调
private SetProgressBarValueCallBack setProgressBarValueCallBack;
 
private TcpClient myTcpClient;  //声明TCP客户端
private NetworkStream netStream;    //声明网络数据流
private Thread receiveDataThread;   //声明接收数据进程
 
 
public frmMain()
{
InitializeComponent();
}
 
private void frmMain_Load(object sender, EventArgs e)
{
//初始化回调//实例化委托
showReceiveMsgCallBack = new ShowReceiveMsgCallBack(AddMsgToList);
//初始化回调
setProgressBarValueCallBack = new SetProgressBarValueCallBack(SetProgressBarValue);
}
 
private void btnConnect_Click(object sender, EventArgs e)
{
//创建并实例化IP终结点
IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse(txtServerIp.Text), Convert.ToInt32(txtServerPort.Text));
//实例化TCP客户端
myTcpClient = new TcpClient();
try
{
//发起TCP连接
myTcpClient.Connect(iPEndPoint);
//获取绑定的网络数据流
netStream = myTcpClient.GetStream();
//实例化接收数据进程
receiveDataThread = new Thread(ReceiveMsg);
receiveDataThread.Start();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
 
}
 
//接收消息线程
private void ReceiveMsg()
{
MessageBox.Show("客户端已连接服务器!");
 
while (true)
{
try
{
//获取数据
byte[] getData = new byte[1024];
netStream.Read(getData,0,getData.Length);
//转换为字符串形式
string strMsg = Encoding.Default.GetString(getData);
//将接收的消息添加到列表中//调用回调
lstReceiveMsg.Invoke(showReceiveMsgCallBack,strMsg);
//改变进度条
pgMsg.Invoke(setProgressBarValueCallBack);
}
catch(ThreadAbortException)
{
 
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
//释放相关资源
if(netStream != null)
{
netStream.Dispose();
}
break;
}
}
}
 
//回调函数的实现函数//被委托的函数
private void AddMsgToList(string text)
{
lstReceiveMsg.Items.Add(text);
}
 
//回调函数的实现函数
private void SetProgressBarValue()
{
if (pgMsg.Maximum == pgMsg.Value)
{
pgMsg.Value = 1;
}
else
{
pgMsg.Value++;
}
}
 
private void btnSendMsg_Click(object sender, EventArgs e)
{
byte[] sendData;
sendData=Encoding.Default.GetBytes(txtMsg.Text);
netStream.Write(sendData,0,sendData.Length);
}
 
private void btnDisConnect_Click(object sender, EventArgs e)
{
//销毁TCP客户端和网络数据流的实例
myTcpClient.Close();
netStream.Dispose();
receiveDataThread.Abort();
}
 
 
}
}

TCP服务端:

界面:

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
 
namespace CSharp_003服务端
{
public partial class frmMain : Form
{
//定义回调//定义委托
private delegate void ShowReceiveMsgCallBack(string text);
//声明回调//声明委托
private ShowReceiveMsgCallBack showReceiveMsgCallBack;
 
private TcpListener server;   //声明Tcp监听对象
private Thread tcpListenerThread;   //声明Tcp监听线程
private Int32 port;     //端口号
private IPAddress localAddr;    //本地IP地址
private Thread receiveDataThread;   //声明接收数据的线程
 
public frmMain()
{
InitializeComponent();
}
 
private void btnListen_Click(object sender, EventArgs e)
{
string strPort = txtServerPort.Text;
if (strPort == "")
{
MessageBox.Show("请输入监听端口");
return;
}
try
{
// 设置监听的端口
port = Int32.Parse(strPort);
localAddr = IPAddress.Parse("127.0.0.1");
if (port > 0)
{
//启动服务端监听线程
tcpListenerThread = new Thread(StartListenerTcp);
tcpListenerThread.Start();
}
else
MessageBox.Show("监听端口号必须大于0,建议使用大于1024的端口");
}
catch (System.Exception ex)
{
 
}
}
 
//Tcp监听线程的实现函数
private void StartListenerTcp()
{
server = new TcpListener(localAddr, port);
server.Start(); // 开始监听客户端的申请
MessageBox.Show("服务已启动。。。");
 
 
try
{
//启动接收数据的线程
receiveDataThread = new Thread(ReceiveMsg);
receiveDataThread.Start();
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
receiveDataThread.Abort();
}
 
}
 
//接收消息线程的实现函数
private void ReceiveMsg()
{
TcpClient client = server.AcceptTcpClient();
NetworkStream netStream = client.GetStream();
while (true)
{
try
{
netStream = client.GetStream();
//获取数据
byte[] getData = new byte[1024];
netStream.Read(getData, 0, getData.Length);
//转换为字符串形式
string strMsg = Encoding.Default.GetString(getData);
//将接收的消息添加到列表中//调用回调
lstReceiveMsg.Invoke(showReceiveMsgCallBack, strMsg);
//将数据返回
netStream.Write(getData, 0, getData.Length);
}
catch (ThreadAbortException)
{
 
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
//释放相关资源
if (netStream != null)
{
netStream.Dispose();
}
break;
}
}
}
 
 
 
//回调函数的实现函数//被委托的函数
private void AddMsgToList(string text)
{
lstReceiveMsg.Items.Add(text);
}
 
private void frmMain_Load(object sender, EventArgs e)
{
//初始化回调//实例化委托
showReceiveMsgCallBack = new ShowReceiveMsgCallBack(AddMsgToList);
}
}
}
作者:
出处:
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
分类: 
标签: 
本文转自韩兆新博客博客园博客,原文链接:http://www.cnblogs.com/hanzhaoxin/archive/2013/02/19/2916886.html,如需转载请自行联系原作者
你可能感兴趣的文章
stream classdesc serialVersionUID = -7218828885279815404, local class serialVersionUID = 1.
查看>>
ZAB与Paxos算法的联系与区别
查看>>
java 读取本地的json文件
查看>>
Breaking parallel loops in .NET C# using the Stop method z
查看>>
Android Content Provider Guides
查看>>
修改故障转移群集心跳时间
查看>>
[轉]redis;mongodb;memcache三者的性能比較
查看>>
微软职位内部推荐-Sr DEV
查看>>
用计算器计算“异或CRC”
查看>>
让你的WPF程序在Win7下呈现Win8风格主题
查看>>
JDBC二查询(web基础学习笔记八)
查看>>
监听器(web基础学习笔记二十二)
查看>>
802.11 学习笔记
查看>>
Leetcode-Database-176-Second Highest Salary-Easy(转)
查看>>
构建Docker Compose服务堆栈
查看>>
最小角回归 LARS算法包的用法以及模型参数的选择(R语言 )
查看>>
Hadoop生态圈-Kafka常用命令总结
查看>>
如何基于Redis Replication设计并实现Redis-replicator?
查看>>
Linux 环境下 PHP 扩展的编译与安装 以 mysqli 为例
查看>>
浮点数内存如何存储的
查看>>