簡體   English   中英

VB.net客戶端和Java服務器之間的TCP / IP通信

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

我的要求是將VB.net用作客戶端,將Java用作服務器以通過TCP / IP進行字符串通信。 我嘗試了各種方法,但沒有得到理想的結果。 我的初步分析說,這是因為來自Client的字符串以字節為單位,而Server的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");

您是否要在任何基於MML(人機語言)的程序中工作? 在這種情況下,請與他人分享您的問題。 我將在基於MML的接口上工作,該接口需要TCP / IP連接,並且我的客戶端將使用Java。

由於缺乏我的觀點,我目前無法添加評論。 希望讀者不要理會。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM