在做項(xiàng)目的過(guò)程中,本來(lái)是想使用JAVA的comm.jar工具實(shí)現(xiàn)串口通訊,不知道怎么回事,總是取不到電腦的串口。所以,改為現(xiàn)在的這種模式:java通過(guò)socket給vb程序發(fā)送指令,然后VB程序通過(guò)comm部件給串口發(fā)送指令。效果不錯(cuò)。
程序服務(wù)端使用VB實(shí)現(xiàn):
代碼:
Private lngWSKIndex As Long
Private Sub Form_Load()
lvRecord.ColumnHeaders.Clear
lvRecord.ColumnHeaders.Add , , "ID", lvRecord.Width / 15
lvRecord.ColumnHeaders.Add , , "客戶端序列號(hào)", lvRecord.Width / 4
lvRecord.ColumnHeaders.Add , , "內(nèi)容", lvRecord.Width
lvRecord.ListItems.Clear
wskServer(0).LocalPort = 9999
wskServer(0).Listen
lngWSKIndex = 0
If MSComm1.PortOpen = True Then
MSComm1.PortOpen = False
Else
End If
MSComm1.CommPort = 1
MSComm1.Settings = "9600,n,8,1"
MSComm1.PortOpen = True
End Sub
Private Sub wskServer_Close(Index As Integer)
If Index = 0 Then Exit Sub
'關(guān)閉客戶端對(duì)應(yīng)的應(yīng)答Socket
Close #Index
'卸載自動(dòng)加載控件,節(jié)省資源
Unload wskServer(Index)
End Sub
'服務(wù)器端接收到連接請(qǐng)求
Private Sub wskServer_ConnectionRequest(Index As Integer, ByVal requestID As Long)
lngWSKIndex = lngWSKIndex + 1 '連接號(hào)自動(dòng)加1
Load wskServer(lngWSKIndex) '加載客戶端連接請(qǐng)求對(duì)應(yīng)的應(yīng)答Socket
wskServer(lngWSKIndex).Accept requestID '允許連接
End Sub
Private Sub wskServer_DataArrival(Index As Integer, ByVal bytesTotal As Long)
Dim strGetData As String
Dim nCount As Integer
Dim i As Integer
wskServer(Index).GetData strGetData, vbString
nCount = lvRecord.ListItems.Count
nCount = nCount + 1
If strGetData = "1=1" Then
lvRecord.ListItems.Add , , nCount
lvRecord.ListItems(nCount).ListSubItems.Add , , "接收到第" & Index & "個(gè)警報(bào)"
lvRecord.ListItems(nCount).ListSubItems.Add , , "未結(jié)賬通過(guò)"
End If '只對(duì)接收到的客戶端發(fā)送命令
' wskServer(Index).SendData "信息:" & strGetData & "已收到!"
Dim Temp(0) As Byte
Dim strBuff As String
strBuff = strGetData
MSComm1.Output = strBuff
End Sub
需要添加Winsock部件和MSComm部件
程序的客戶端JAVA代碼
package com;
import java.io.*;
import java.net.*;
public class Socket_t {
public static void main(String args[]){
try {
Socket_t.SendData("1=1");
Thread.sleep(10000L);
Socket_t.SendData("1=0");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void SendData(String data){
try{
Socket socket=new Socket("127.0.0.1",9999);
BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
PrintWriter os=new PrintWriter(socket.getOutputStream());
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
os.write(data);
os.flush();
os.close(); //關(guān)閉Socket輸出流
socket.close(); //關(guān)閉Socket
}catch(Exception e){
e.printStackTrace();
}
}
}
聯(lián)系客服