当前位置:网站首页>c#利用 TCP 协议建立连接
c#利用 TCP 协议建立连接
2022-07-07 12:10:00 【孔雀东南飞-深圳】
背景:有一个部署在 树莓派 上的一个服务器 需要用 windows 系统与其建立连接 数据格式为 json 格式 所以本文只有客户端的代码:
1 声明一个全局变量
Socket socket = null;
2 在 mainWindow 中写:
IPAddress ipadr = IPAddress.Parse("192.168.2.42"); //---ip地址为服务端地址
socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
try
{
socket.Connect(ipadr,1616); //------------需要看服务端有没有设置端口号
}catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine("连接服务器失败 请按回车键退出!");
return;
}
3 按钮触发事件
private void Button_Click(object sender, RoutedEventArgs e)
{
//----定义json数据格式
Comand com = new Comand(); //------需要额外定义类 类有两个属性 都是 string 型
com.SendCmd = "1";
com.msg = "null";
string jsonData = JsonConvert.SerializeObject(com); //----需要额外在 程序包管理器控制台导入包 否则报错
socket.Send(Encoding.ASCII.GetBytes(jsonData));
try
{
Thread receiveThread = new Thread(ReceiveMessage); //----接收消息的方法下文有定义
receiveThread.Start(receiveThread);
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
4 ReceiveMessage 方法
public void ReceiveMessage(object obj)
{
try
{
byte[] bt = new byte[1024];
int len = socket.Receive(bt);
string data = Encoding.ASCII.GetString(bt,0,len);
listBox.Dispatcher.BeginInvoke( //----开始委托
new Action(() => { listBox.Items.Add("\r\n 接收到的数据:" + data);}),null);
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine("接受失败 请确认是否断联!");
// receiveSocket.Shutdown(SocketShutdown.Both);
// receiveSocket.Close();
return;
}
}
ps:有一个缺点就是 树莓派 那边会自己黑屏 再次打开的时候需要重开软件 windows这边把连接写在主方法里面 也就是说树莓派那边重新开开 这边 windows 的软件也要重新打开 重新连接 这是一个不好的点
边栏推荐
- PC端页面如何调用QQ进行在线聊天?
- 作战图鉴:12大场景详述容器安全建设要求
- Excuse me, why is it that there are no consumption messages in redis and they are all piled up in redis? Cerely is used.
- 2022-7-7 Leetcode 34.在排序数组中查找元素的第一个和最后一个位置
- . Net core about redis pipeline and transactions
- Excuse me, I have three partitions in Kafka, and the flinksql task has written the join operation. How can I give the join operation alone
- 【面试高频题】难度 2.5/5,简单结合 DFS 的 Trie 模板级运用题
- Excuse me, when using Flink SQL sink data to Kafka, the execution is successful, but there is no number in Kafka
- Xshell connection server changes key login to password login
- 内存溢出和内存泄漏的区别
猜你喜欢
Sliding rail stepping motor commissioning (national ocean vehicle competition) (STM32 master control)
[fortress machine] what is the difference between cloud fortress machine and ordinary fortress machine?
Best practice | using Tencent cloud AI willingness to audit as the escort of telephone compliance
最长上升子序列模型 AcWing 1014. 登山
Co create a collaborative ecosystem of software and hardware: the "Joint submission" of graphcore IPU and Baidu PaddlePaddle appeared in mlperf
. Net core about redis pipeline and transactions
交付效率提升52倍,运营效率提升10倍,看《金融云原生技术实践案例汇编》(附下载)
Leetcode simple question sharing (20)
社会责任·价值共创,中关村网络安全与信息化产业联盟对话网信企业家海泰方圆董事长姜海舟先生
js 获取当前时间 年月日,uniapp定位 小程序打开地图选择地点
随机推荐
Battle Atlas: 12 scenarios detailing the requirements for container safety construction
请问指南针股票软件可靠吗?交易股票安全吗?
【日常训练--腾讯精选50】231. 2 的幂
Move base parameter analysis and experience summary
Toraw and markraw
XML文件的解析操作
Did login metamask
请问,在使用flink sql sink数据到kafka的时候出现执行成功,但是kafka里面没有数
华为镜像地址
Huawei image address
Take you to master the three-tier architecture (recommended Collection)
What parameters need to be reconfigured to replace the new radar of ROS robot
mysql导入文件出现Data truncated for column ‘xxx’ at row 1的原因
高等數學---第八章多元函數微分學1
现在网上开户安全么?那么网上开户选哪个证券公司?
2022-7-7 Leetcode 844. Compare strings with backspace
得物客服热线的演进之路
3D Detection: 3D Box和点云 快速可视化
Cesium 已知一点经纬度和距离求另一个点的经纬度
Is it safe to open an account online now? Which securities company should I choose to open an account online?