很奇怪Java怎么都遍历不到输出方向的串口,如下图所示
然后
用Java就无法成功发出数据,想了半天没想到解决方法,索性就用c++传,c++很给力,能成功连接串口,于是就用c++作为服务端,Java作为客户端,这里只需要自己编写自己对应部分的代码就ok,
麻烦的是Java向c++传指令时要注意在数据后面加一个 ,因为c中数据是以这个结尾的,另外char型数组要用num【number】形式来比较。
c++代码如下
#include <WINSOCK2.H> #include <stdio.h> #include<iostream> #include<windows.h> #define PORT 5150 #define MSGSIZE 1024 #pragma comment(lib, "ws2_32.lib") using namespace std; int main() { HANDLE hcom; hcom = CreateFile("COM2",GENERIC_READ | GENERIC_WRITE,0,NULL,OPEN_EXISTING ,FILE_ATTRIBUTE_NORMAL,NULL); SetupComm(hcom,4096,4096); DCB dcb; GetCommState(hcom,&dcb); dcb.BaudRate = 9600; dcb.ByteSize = 8; dcb.Parity = 0; dcb.StopBits = 1; SetCommState(hcom,&dcb); char stop[]="$0,0,0#"; char forward[]="$1,0,0#"; char backoff[]="$2,0,0#"; char left_turn[]="$3,0,0#"; char right_turn[]="$4,0,0#"; DWORD dwWrittenLen = 0; //int k=0; WSADATA wsaData; SOCKET sListen; SOCKET sClient; SOCKADDR_IN local; SOCKADDR_IN client; char szMessage[MSGSIZE]; //char szMessage; int a; int ret; int iaddrSize = sizeof(SOCKADDR_IN); WSAStartup(0x0202, &wsaData); sListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); local.sin_family = AF_INET; local.sin_port = htons(5150); local.sin_addr.s_addr = htonl(INADDR_ANY); bind(sListen, (struct sockaddr *) &local, sizeof(SOCKADDR_IN)); listen(sListen, 1); sClient = accept(sListen, (struct sockaddr *) &client, &iaddrSize); printf("Accepted client:%s:%d ", inet_ntoa(client.sin_addr), ntohs(client.sin_port)); while (TRUE) { if(ret = recv(sClient, szMessage, MSGSIZE, 0)) { ret = recv(sClient, szMessage, MSGSIZE, 0); szMessage[ret] = '