简体   繁体   English

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

[英]TCP/IP Communication between VB.net Client and Java Server

My requirement is to use VB.net as Client and Java as Server for String Communication through TCP/IP. 我的要求是将VB.net用作客户端,将Java用作服务器以通过TCP / IP进行字符串通信。 I tried various things but I am not getting desired result. 我尝试了各种方法,但没有得到理想的结果。 My preliminary analysis says that it's because the string coming from Client is coming as bytes while Server's readLine Method reads string in form of characters and hence it's not able to recognize the new line character to terminate readLine. 我的初步分析说,这是因为来自Client的字符串以字节为单位,而Server的readLine方法以字符形式读取字符串,因此无法识别换行符以终止readLine。 I have tried various mehtods, even vbCrLf but it's not able to recognize the characters properly. 我尝试了各种方法,甚至vbCrLf,但它无法正确识别字符。 I cannot use read(byte[]) in java as the server is being used for multiple applications which sends various length strings. 我不能在Java中使用read(byte []),因为服务器正被用于发送各种长度字符串的多个应用程序。 Please guide me regarding without changing server code how can I achieve this. 请指导我有关如何不更改服务器代码的情况。 Client and Server Code are given below. 客户端和服务器代码如下。 I am attaching sample working java client code as well. 我还将附加示例工作的Java客户端代码。

VB.net Client Code : 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 Server Code : 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();
            }
        }
    }
}

Working Java Client Code : 有效的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();
    }
}

Your VB-Client is using UTF-8 as encoding while your Java code does not specify any. 您的VB客户端使用UTF-8作为编码,而您的Java代码未指定任何编码。 This means that your server is using the platform default, which is CP-1252 on Windows. 这意味着您的服务器使用的平台默认值为Windows上的默认平台CP-1252。

Replace this line 替换此行

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

with this 有了这个

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

are you trying to work in any MML(Man-Machine-Language) based program? 您是否要在任何基于MML(人机语言)的程序中工作? Please share your problems in that case for others. 在这种情况下,请与他人分享您的问题。 I am going to work on an MML based interface which requires TCP/IP connections and my client is going to be in Java. 我将在基于MML的接口上工作,该接口需要TCP / IP连接,并且我的客户端将使用Java。

Due to the lack of my points, i can not add comments at the moment. 由于缺乏我的观点,我目前无法添加评论。 I hope readers would ignore. 希望读者不要理会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM