powered by simpleCommunicator - 2.0.61     © 2026 Programmizd 02
Целевая тема:
Создать новую тему:
Автор:
Закрыть
Цитировать
Форумы / Java [игнор отключен] [закрыт для гостей] / работа с usb/сом портами
5 сообщений из 5, страница 1 из 1
работа с usb/сом портами
    #35940281
fabler
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
всем добрый день!

никак не получается наладить взаимодействие двух программ через СОМ порт.
использую бибилиотеку от rxtx.org, на их же сайте есть примеры SimpleReader и SimpleWriter.
пытаюсь сделать так, чтобы программа SimpleReader все-таки прочитала то, что SimpleWriter туда написал...

но получается, что какая-либо из программ пишет, что Port in use. Вроде как логично, что они должны использоватьодин порт: один на прием, одни на передачу.

буду признателен совету!
вообще есть задча непрерывной передачи массива данных из программы в мобильное устройство, но пока решил локально разобрать, что не так

передатчик
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
 package  main;

 import  java.io.*;
 import  java.util.*;
 import  gnu.io.*;


 public   class  SimpleWrite {
     static  Enumeration	      portList;
     static  CommPortIdentifier portId;
     static  String	      messageString = "Hello, world!";
     static  SerialPort	      serialPort;
     static  OutputStream       outputStream;
     static  DataOutputStream    dos ;
     static   boolean 	      outputBufferEmptyFlag = false;

     public   static   void  main(String[] args) {
	 boolean  portFound = false;
	String  defaultPort = "COM3";

	 if  (args.length >  0 ) {
	    defaultPort = args[ 0 ];
	}
	portList = CommPortIdentifier.getPortIdentifiers();
	 while  (portList.hasMoreElements()) {
	    portId = (CommPortIdentifier) portList.nextElement();
        System.out.println(portId.getName());
         if  (portId.getName().equals(defaultPort)) {
		    System.out.println("Found port " + defaultPort);
		    portFound = true;
		     try  {
			serialPort =
			    (SerialPort)portId.open("SimpleWrite",  2000 );
		    }  catch  (PortInUseException e) {
			System.out.println("Port in use.");
			 continue ;
		    }
		     try  {
			outputStream = serialPort.getOutputStream();
		    }  catch  (IOException e) {}
		     try  {
			serialPort.setSerialPortParams( 9600 ,
						       SerialPort.DATABITS_8,
						       SerialPort.STOPBITS_1,
						       SerialPort.PARITY_NONE);
		    }  catch  (UnsupportedCommOperationException e) {}
		     try  {
		    	serialPort.notifyOnOutputEmpty(true);
		    }  catch  (Exception e) {
			System.out.println("Error setting event notification");
			System.out.println(e.toString());
			System.exit(- 1 );
		    }
		    System.out.println(
		    	"Writing \""+messageString+"\" to "
			+serialPort.getName());

		     try  {
			outputStream.write(messageString.getBytes());
		    }  catch  (IOException e) {}

		     try  {
		       Thread.sleep( 2000 );  // Be sure data is xferred before closing
		    }  catch  (Exception e) {}
		    serialPort.close();
		    System.exit( 1 );
		}  
	}
    }
}



приемник
Код: plaintext
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.
80.
81.
82.
83.
84.
85.
86.
87.
88.
89.
90.
91.
92.
93.
94.
95.
96.
97.
 package  main;

 import  gnu.io.*;
 import  java.io.*;


 import  java.util.Enumeration;
 import  java.util.TooManyListenersException;



 public   class  COMServer  implements  Runnable, SerialPortEventListener{
     static  CommPortIdentifier portId;
     static  Enumeration	      portList;
     private  InputStream		      inputStream;
     private  SerialPort		      serialPort;
     private  Thread		      readThread;

     public  COMServer(String portName){
        System.out.println(portName +" is under control...");
         while  (true) {
             try  {
                serialPort = (SerialPort)portId.open("SimpleReadApp",  2000 );
            }  catch  (PortInUseException e1) {
                e1.printStackTrace();
            }
             try  {
                inputStream = serialPort.getInputStream();
            }  catch  (IOException e2) {
                e2.printStackTrace();
            }
             try  {
                serialPort.addEventListener( this );
            }  catch  (TooManyListenersException e3) {
                e3.printStackTrace();
            }
            serialPort.notifyOnDataAvailable(true);
             try  {
                serialPort.setSerialPortParams( 9600 , SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
            }  catch  (UnsupportedCommOperationException e4) {
                e4.printStackTrace();
            }
            readThread =  new  Thread( this );
            readThread.start();
        }
    }

     public   void  run() {
         try  {
            Thread.sleep( 20000 );
        }  catch  (InterruptedException e) {
            e.printStackTrace();
        }
    }

     public   void  serialEvent(SerialPortEvent event) {
         switch  (event.getEventType()) {
        	 case  SerialPortEvent.BI:
             case  SerialPortEvent.OE:
        	 case  SerialPortEvent.FE:
        	 case  SerialPortEvent.PE:
        	 case  SerialPortEvent.CD:
             case  SerialPortEvent.CTS:
             case  SerialPortEvent.DSR:
             case  SerialPortEvent.RI:
             case  SerialPortEvent.OUTPUT_BUFFER_EMPTY:  break ;
             case  SerialPortEvent.DATA_AVAILABLE:
                 byte [] readBuffer =  new   byte [ 20 ];
                 try  {
                     while  (inputStream.available() >  0 ) {
                         int  numBytes = inputStream.read(readBuffer);
                    }
                    System.out.print( new  String(readBuffer));
                }  catch  (IOException e) {
                    e.printStackTrace();
                }
                 break ;
        }
    }



     public   static   void  main(String[] args) {
         boolean 	portFound = false;
        String defaultPort = "COM3";
        portList = CommPortIdentifier.getPortIdentifiers();
         while  (portList.hasMoreElements()) {
            portId = (CommPortIdentifier)portList.nextElement();
             if  (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                 if  (portId.getName().equals(defaultPort)) {
                    System.out.println("Found port");
                    portFound = true;
                    COMServer com =  new  COMServer(defaultPort);
                }
            }
        }
    }
}
...
Рейтинг: 0 / 0
работа с usb/сом портами
    #35941815
BlueJacket
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
авторно получается, что какая-либо из программ пишет, что Port in use. Вроде как логично, что они должны использоватьодин порт: один на прием, одни на передачу.

Нет, не логично. Для того чтобы это заработало на одной машине надо:
1 Два порта соединенных кабелем Null-modem.
2 Модули должны использовать разные порты для работы.
3 Параметры работы портов должны быть согласованы (скорость, четность, ... , ну это вроде нормально)
Удачи
...
Рейтинг: 0 / 0
работа с usb/сом портами
    #35941991
fabler
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Участник
BlueJacket,

точно... как сам не додумался... :)
делал по аналогии с сокетами...

ладно, тогда такое тестирование можно опустить, буду тестировать напрямую с мобильником.
спасибо, что сняли с ручника %)
...
Рейтинг: 0 / 0
работа с usb/сом портами
    #36103882
algepv
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
fabler,
Добрый день!
Подскажите, где вы взяли библиотеки для работы с ком портом?
...
Рейтинг: 0 / 0
Период между сообщениями больше года.
работа с usb/сом портами
    #39470277
Tsyklop
Скрыть профиль Поместить в игнор-лист Сообщения автора в теме
Гость
fabler,

Подскажете как работать с rxtx? пожалуйста
...
Рейтинг: 0 / 0
5 сообщений из 5, страница 1 из 1
Форумы / Java [игнор отключен] [закрыт для гостей] / работа с usb/сом портами
Найденые пользователи ...
Разблокировать пользователей ...
Читали форум (0):
Пользователи онлайн (0):
x
x
Закрыть


Просмотр
0 / 0
Close
Debug Console [Select Text]