Vinod Maurya
Vinod Maurya

Reputation: 4167

How to use socket in Java

I am having some trouble using sockets in Java. I am creating an application that continually needs to send the data to a server. The data is sent through the socket from client. I am using following code:

serverAddr = InetAddress.getByName(ipAddress);

while(send)
{
    soc=new Socket(serverAddr,8210);
    outStream=soc.getOutputStream();
    outStream.write(data);
    outStream.close();
}

The above code is working fine and there is no issue with this. Here I am creating a new object of Socket in every loop and I think this is not a good implementation method. How can I send the data to server using one Socket? (I don't want to create a new object in every loop)

And here is the code of server that I had written in C#:

while (true)
{
    Socket s = listener.AcceptSocket();
    NetworkStream ns = new NetworkStream(s);
    int d;
    while ((d = ns.ReadByte()) >= 0)
    {
        //Process data here
    }
    s.Close();
}

Also what modification I need to do in server side?

Thanks

Upvotes: 2

Views: 353

Answers (1)

Adrian Cox
Adrian Cox

Reputation: 6334

Remember that creating a new socket object will also create a new TCP connection. If you want to use a single connection, preserve the output stream. You'll need to consider cleanup on exceptions, and you may also need a further layer around this for recovery if there is a transient network failure in between.

serverAddr = InetAddress.getByName(ipAddress);


soc=new Socket(serverAddr,8210);
try {
    outStream=soc.getOutputStream();
    while(send)
    {
        outStream.write(data);
    } 
    outStream.close();
} finally {
    soc.close();
}

For the server side: your code is basically correct, but you also need to consider cleanup (use using), and as Marc Gravell points out, you need to be sure you can find the message boundaries when you are using a single TCP connection.

Upvotes: 2

Related Questions