Chintan Adhia
Chintan Adhia

Reputation: 91

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. 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. I have tried various mehtods, even vbCrLf but it's not able to recognize the characters properly. I cannot use read(byte[]) in java as the server is being used for multiple applications which sends various length strings. 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.

VB.net Client Code :

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 :

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 :

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();
    }
}

Upvotes: 1

Views: 2402

Answers (2)

Hammad Dar
Hammad Dar

Reputation: 515

are you trying to work in any MML(Man-Machine-Language) based program? 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.

Due to the lack of my points, i can not add comments at the moment. I hope readers would ignore.

Upvotes: 0

Steven Pessall
Steven Pessall

Reputation: 993

Your VB-Client is using UTF-8 as encoding while your Java code does not specify any. This means that your server is using the platform default, which is CP-1252 on Windows.

Replace this line

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

with this

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

Upvotes: 2

Related Questions