gpt4 book ai didi

java - VB.net 客户端和 Java 服务器之间的 TCP/IP 通信

转载 作者:可可西里 更新时间:2023-11-01 02:52:02 27 4
gpt4 key购买 nike

我的要求是使用 VB.net 作为客户端,使用 Java 作为服务器,通过 TCP/IP 进行字符串通信。我尝试了各种方法,但没有得到想要的结果。初步分析是因为客户端传过来的字符串是字节,而服务器的readLine方法是读取字符形式的字符串,所以无法识别换行符来终止readLine。我尝试了各种方法,甚至是 vbCrLf,但它无法正确识别字符。我不能在 java 中使用 read(byte[]),因为服务器被用于发送各种长度字符串的多个应用程序。请指导我如何在不更改服务器代码的情况下实现这一目标。客户端和服务器代码如下。我也附上了示例工作 Java 客户端代码。

VB.net 客户端代码:

Imports System.Net.Sockets
Imports System.Text
Imports System.Threading
Imports System.IO

Public Class Form1
Inherits System.Windows.Forms.Form
Dim clientSocket As New TcpClient
Dim serverStream As NetworkStream
#Region " Windows Form Designer generated code "

Public Sub New()
MyBase.New()

'This call is required by the Windows Form Designer.
InitializeComponent()

'Add any initialization after the InitializeComponent() call

End Sub

'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub

'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer

'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents Button1 As System.Windows.Forms.Button
Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.Label1 = New System.Windows.Forms.Label
Me.Button1 = New System.Windows.Forms.Button
Me.TextBox1 = New System.Windows.Forms.TextBox
Me.SuspendLayout()
Me.Label1.Location = New System.Drawing.Point(8, 32)
Me.Label1.Name = "Label1"
Me.Label1.Size = New System.Drawing.Size(272, 64)
Me.Label1.TabIndex = 0
Me.Button1.Location = New System.Drawing.Point(88, 200)
Me.Button1.Name = "Button1"
Me.Button1.TabIndex = 1
Me.Button1.Text = "Enter"
Me.TextBox1.Location = New System.Drawing.Point(80, 144)
Me.TextBox1.Name = "TextBox1"
Me.TextBox1.TabIndex = 2
Me.TextBox1.Text = ""
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(292, 273)
Me.Controls.Add(Me.TextBox1)
Me.Controls.Add(Me.Button1)
Me.Controls.Add(Me.Label1)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub

#End Region

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
msg("Client Started")
clientSocket.Connect("localhost", 4447)
Label1.Text = "Client Socket Program - Server Connected .."
Catch ex As Exception
msg("Exception occurred while connecting to server")
End Try
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim sMsgToHost As String
Dim bw As New IO.BinaryWriter(clientSocket.GetStream)
sMsgToHost = "Sending a Test String" + vbCrLf
bw.Write(sMsgToHost)
bw.Flush()
Thread.Sleep(5000)
Dim reader As New BinaryReader(clientSocket.GetStream)
Dim bytes(clientSocket.ReceiveBufferSize) As Byte
reader.Read(bytes, 0, CInt(clientSocket.ReceiveBufferSize))
Dim returndata As String = Encoding.UTF8.GetString(bytes)
reader.Close()
clientSocket.Close()
serverStream.Close()
Catch ex As Exception
msg("Exception occurred while sending and recieving data")
End Try
End Sub
Sub msg(ByVal mesg As String)
Label1.Text = ""
Label1.Text = mesg
End Sub
End Class

Java 服务器代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServerTest {
public static void main(String[] args) {
int port = 4447;
PrintWriter out = null;
BufferedReader in = null;
String strTempString = null;
StringBuffer sbInputStringBuf = null;
String tempString1 = null;
String strResponse = null;
Socket socket = null;
try{
ServerSocket serverSocket = new ServerSocket(port);
while(true){
socket = serverSocket.accept();
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Waiting for Message123.");
while ((strTempString = in.readLine()) != null && !strTempString.equals("")){
if(sbInputStringBuf == null){
sbInputStringBuf = new StringBuffer();
}
sbInputStringBuf.append(strTempString);
}
tempString1 = sbInputStringBuf.toString();
System.out.println("Request is : " + tempString1);
strResponse = "The Sent String was : " + tempString1;
out.println(strResponse + "\n");
out.flush();
}
}
catch (Exception e) {
e.printStackTrace();
}
finally{
try{
out.close();
in.close();
socket.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
}

工作 Java 客户端代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {

public static void main(String[] args) throws IOException{

Socket socket = null;
String host = "10.122.1.27";
int port = 4447;
PrintWriter out = null;
BufferedReader in = null;
String fromServer;
String fromUser;

try {
System.out.println("Inside main() of TCPClient");
socket = new Socket(host, port);
System.out.println("Socket Created...");
out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("out Object Created...");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("in Object Created...");
}

catch (UnknownHostException e) {
System.out.println("Don't know about host : " + host);
e.printStackTrace();
System.exit(1);
}

catch (IOException e) {
System.out.println("Couldn't get I/O for the connection to : " + host);
e.printStackTrace();
System.exit(1);
}

fromUser="NSDL|AFAPL2503G\n";
System.out.println("Sending : " + fromUser);
out.println(fromUser); // Writing the PAN in output stream

/* Reading the NSDL response from input stream */
if((fromServer = in.readLine()) != null){
System.out.println("From Server : " + fromServer);
}

out.write(fromServer);
out.close();
in.close();
socket.close();
}
}

最佳答案

您的 VB 客户端使用 UTF-8 作为编码,而您的 Java 代码未指定任何编码。这意味着您的服务器正在使用平台默认值,即 Windows 上的 CP-1252。

替换这一行

in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

有了这个

in = new BufferedReader(new InputStreamReader(socket.getInputStream()), "UTF-8");

关于java - VB.net 客户端和 Java 服务器之间的 TCP/IP 通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22764336/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com