当前位置:网站首页>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 的软件也要重新打开 重新连接 这是一个不好的点
边栏推荐
- Introduction to database system - Chapter 1 introduction [conceptual model, hierarchical model and three-level mode (external mode, mode, internal mode)]
- SSRF vulnerability file pseudo protocol [netding Cup 2018] fakebook1
- Drawerlayout suppress sideslip display
- Parameter keywords final, flags, internal, mapping keywords internal
- requires php ~7.1 -> your PHP version (7.0.18) does not satisfy that requirement
- 得物客服热线的演进之路
- 2022-7-6 Leetcode 977.有序数组的平方
- Lavarel之环境配置 .env
- Laravel5 call to undefined function OpenSSL cipher IV length() error php7 failed to open OpenSSL extension
- What parameters need to be reconfigured to replace the new radar of ROS robot
猜你喜欢
Evolution of customer service hotline of dewu
Redis只能做缓存?太out了!
使用day.js让时间 (显示为几分钟前 几小时前 几天前 几个月前 )
Advanced Mathematics - Chapter 8 differential calculus of multivariate functions 1
Xshell connection server changes key login to password login
2022-7-6 beginner redis (I) download, install and run redis under Linux
SSRF vulnerability file pseudo protocol [netding Cup 2018] fakebook1
Flask session forged hctf admin
高等數學---第八章多元函數微分學1
LeetCode简单题分享(20)
随机推荐
Help tenants
MySQL "invalid use of null value" solution
Beginner XML
Oracle advanced (V) schema solution
Excusez - moi, l'exécution a été réussie lors de l'utilisation des données de puits SQL Flink à Kafka, mais il n'y a pas de nombre dans Kafka
AutoCAD - how to input angle dimensions and CAD diameter symbols greater than 180 degrees?
Toraw and markraw
"Song of ice and fire" in the eleventh issue of "open source Roundtable" -- how to balance the natural contradiction between open source and security?
The reason why data truncated for column 'xxx' at row 1 appears in the MySQL import file
Thread pool reject policy best practices
Details of redis core data structure & new features of redis 6
Common response status codes
使用day.js让时间 (显示为几分钟前 几小时前 几天前 几个月前 )
Vmware共享主机的有线网络IP地址
[AI practice] Application xgboost Xgbregressor builds air quality prediction model (II)
社会责任·价值共创,中关村网络安全与信息化产业联盟对话网信企业家海泰方圆董事长姜海舟先生
Use day JS let time (displayed as minutes, hours, days, months, and so on)
Transferring files between VMware and host
2022-7-6 beginner redis (I) download, install and run redis under Linux
Lavarel之环境配置 .env