好吧,我自己来回答我的问题。做之前把这个问题想的太复杂了,其实tcp协议就是tcp协议,哪个平台都一样
先放 Arduino的代码
-
- char tcpbuffer[1024];
- int bufferlen = 1024;
-
- void setup()
- {
-
- //wifi shield
- Serial1.begin(115200);
- Serial.begin(115200);
- }
-
- void loop()
- {
- /** function code here */
-
- if(Serial1.available() > 0)
- {
- int reallen = Serial1.readBytes(tcpbuffer, 1024);
- Serial.write(tcpbuffer,reallen);
- }
-
- }
复制代码
wifi sheild设定的是Tcp Server模式,ip地址 192.168.1.20,端口8899
因为我用的是Leonardo, 所以wifi 用的是Serail1,电脑用Serial,不冲突
客户端用c#代码如下
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Collections.Generic;
- using System.Text;
-
-
- namespace WifiShieldTest
- {
- class MainClass
- {
- public static void Main (string[] args)
- {
- Console.WriteLine ("Hello World!");
-
- //定义发送数据缓存
- byte[] data = new byte[1024];
- //定义字符串,用于控制台输出或输入
- string input, stringData;
- //定义主机的IP及端口
- IPAddress ip = IPAddress.Parse("192.168.1.20");
- IPEndPoint ipEnd = new IPEndPoint(ip, 8899);
- //定义套接字类型
- Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- //尝试连接
- try
- {
- socket.Connect(ipEnd);
- }
- //异常处理
- catch (SocketException e)
- {
- Console.Write("Fail to connect server");
- Console.Write(e.ToString());
- return;
- }
- //定义接收数据的长度
- int recv = 0;
- //将接收的数据转换成字符串
- //stringData = Encoding.ASCII.GetString(data, 0, recv);
-
-
- //定义从键盘接收到的字符串
- input = "test";
-
- //将从键盘获取的字符串转换成整型数据并存储在数组中
- data = Encoding.ASCII.GetBytes(input);
- //发送该数组
- socket.Send(data, data.Length, SocketFlags.None);
-
- Console.Write("disconnect from server");
- socket.Shutdown(SocketShutdown.Both);
- socket.Close();
- }
-
- }
- }
复制代码
客户端程序跑起来,用Arduino IDE的串口查看程序就能看到通过tcp传过来的字符了
|