• Java与c++之socket通信并c++串口输出


    很奇怪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] = '';  
                
        /*
        if(!WriteFile(hcom,data,8,&dwWrittenLen,NULL))
        {
               fprintf(stderr, "发送数据失败!
    ");
        }
        k++; 
        */ 
                        if (szMessage[0]==1){
                            a=2;
                        }
                        else if(szMessage[0]==2){
                            a=3;
                        }
                        else if(szMessage[0]==3){
                            a=1;
                        }
                        else if(szMessage[0]==4){
                            a=4;
                        }
                        else if(szMessage[0]==5){
                            a=5;
                        }
                        
                        
                            switch(a){
                            case 1:    
                                WriteFile(hcom,left_turn,8,&dwWrittenLen,NULL);
                                printf("Received [%d bytes]: '%s'
    ", ret, szMessage); 
                                break;
                            case 2:
                                WriteFile(hcom,forward,8,&dwWrittenLen,NULL);
                                printf("Received [%d bytes]: '%s'
    ", ret, szMessage); 
                                break;
                            case 3:
                                WriteFile(hcom,backoff,8,&dwWrittenLen,NULL);
                                printf("Received [%d bytes]: '%s'
    ", ret, szMessage); 
                                break;
                            case 4:
                                WriteFile(hcom,right_turn,8,&dwWrittenLen,NULL);
                                printf("Received [%d bytes]: '%s'
    ", ret, szMessage);     
                                break;
                            case 5:
                                WriteFile(hcom,stop,8,&dwWrittenLen,NULL);
                                printf("Received [%d bytes]: '%s'
    ", ret, szMessage);     
                                break;
                            }
                    
    /*    if(ret==0x00){
        
        }
         if(ret==1){
            
        }    
         if(ret==11){
            WriteFile(hcom,backoff,8,&dwWrittenLen,NULL);
            printf("Received [%d bytes]: '%s'
    ", ret, szMessage); 
        }
         if(ret==3){
            WriteFile(hcom,left_turn,8,&dwWrittenLen,NULL);
            printf("Received [%d bytes]: '%s'
    ", ret, szMessage); 
        }
         if(ret==4){
            WriteFile(hcom,right_turn,8,&dwWrittenLen,NULL);
            printf("Received [%d bytes]: '%s'
    ", ret, szMessage); 
        }
        */
        /*     
        printf("往串口发送数据成功!第%d次
    " ,k);
        Sleep(1*1000);  //10s发送一次
        printf("Received [%d bytes]: '%s'
    ", ret, szMessage);    
        */
                                        
        }
        }
             return 0;      
      }  

    Java如下 其中监听key 创建一个面板是必要的,只有这样才能一直监听。

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.io.UnsupportedEncodingException;
    import java.net.Socket;
    
    /**
     * @Author:Tianye Long
     * @Description:
     * @Date:2020/1/2 10:38
     * @Version:1.8
     */
    public class ARCar extends JFrame  {
        Socket socket=new Socket("127.0.0.1",5150);
        public static PrintWriter printWriter;
        MyPanel myPanel=null;
        public static void main(String[] args) throws IOException {
            ARCar arCar=new ARCar();
        }
        public ARCar() throws IOException {
            printWriter=new PrintWriter(socket.getOutputStream(), true);
            myPanel=new MyPanel();
            this.add(myPanel);
            this.addKeyListener(myPanel);
            this.setSize(400,200);
            this.setLocation(100,100);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setVisible(true);
        }
    
    
    }
    class MyPanel extends JPanel implements KeyListener{
        char a=1;
        char b=2;
        char c=3;
        char d=4;
        char f=5;
        @Override
        public void paint(Graphics g) {
            super.paint(g);
        }
        @Override
        public void keyTyped(KeyEvent e) {
    
        }
        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_W) {
                for (int i = 0; i <2 ; i++) {
                    ARCar.printWriter.println(a);
                }
    
            } else if (e.getKeyCode() == KeyEvent.VK_S) {
                for (int i = 0; i < 2; i++) {
                    ARCar.printWriter.println(b+"");
                }
    
            } else if (e.getKeyCode() == KeyEvent.VK_A) {
                for (int i = 0; i < 2; i++) {
                    ARCar.printWriter.println(c+"");
                }
    
            } else if (e.getKeyCode() == KeyEvent.VK_D) {
                for (int i = 0; i < 2; i++) {
                    ARCar.printWriter.println(d+"");
                }
    
            }else if (e.getKeyCode() == KeyEvent.VK_F) {
                for (int i = 0; i < 2; i++) {
                    ARCar.printWriter.println(f+"");
                }
    
            }
        }
    
        @Override
        public void keyReleased(KeyEvent e) {
    
        }
    }
  • 相关阅读:
    10年后编程还有意义吗?
    专访Jeffrey Richter:Windows 8是微软的重中之重
    x86汇编指令脚本虚拟机
    基于容器的持续交付管道
    NET Core 整合Autofac和Castle
    数据结构与算法1
    Redis集群
    react + iscroll5
    MongoDB
    WebComponent
  • 原文地址:https://www.cnblogs.com/JLU-Dragon/p/12134593.html
Copyright © 2020-2023  润新知