JAVA与VB通过SOCKET通讯
在做项目的过程中,本来是想使用JAVA的comm.jar工具实现串口通讯,不知道怎么回事,总是取不到电脑的串口。所以,改为现在的这种模式:java通过socket给vb程序发送指令,然后VB程序通过comm部件给串口发送指令。效果不错。
程序服务端使用VB实现:
代码:
Private lngWSKIndex As Long
Private Sub Form_Load()
lvRecord.ColumnHeaders.Clear
lvRecord.ColumnHeaders.Add , , "ID", lvRecord.Width / 15
lvRecord.ColumnHeaders.Add , , "客户端序列号", lvRecord.Width / 4
lvRecord.ColumnHeaders.Add , , "内容", 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
'关闭客户端对应的应答Socket
Close #Index
'卸载自动加载控件,节省资源
Unload wskServer(Index)
End Sub
'服务器端接收到连接请求
Private Sub wskServer_ConnectionRequest(Index As Integer, ByVal requestID As Long)
lngWSKIndex = lngWSKIndex + 1 '连接号自动加1
Load wskServer(lngWSKIndex) '加载客户端连接请求对应的应答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 & "个警报"
lvRecord.ListItems(nCount).ListSubItems.Add , , "未结账通过"
End If '只对接收到的客户端发送命令
' 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(); //关闭Socket输出流
socket.close(); //关闭Socket
}catch(Exception e){
e.printStackTrace();
}
}
}
还没有评论,来说两句吧...