I am writing a simple socket program as shown below. I want to send a byte array to a server socket and readi it at the server end. This is the server
package com.java;
//File Name GreetingServer.java
import java.net.*;
import java.io.*;
public class GreetingsServer extends Thread
{
private ServerSocket serverSocket;
public GreetingsServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println("--"+ server.getReceiveBufferSize());
byte[] b1 = new byte[4] ;
int i =in.read(b1);
System.out.println("i = " + i + "b1 = " +b1);
/* DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");*/
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
int port = Integer.parseInt(args[0]);
try
{
Thread t = new GreetingsServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
This is the client
package com.java;
import java.net.*;
import java.io.*;
public class GreetingClient
{
public static void main(String [] args)
{
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try
{
System.out.println("Connecting to " + serverName
+ " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
byte[] b = {1,2,3,4};
DataOutputStream out =
new DataOutputStream(outToServer);
/*BufferedOutputStream out = new BufferedOutputStream(outToServer);*/
System.out.println("**" + b);
out.write(b);
/*out.writeUTF("Hello from "
+ client.getLocalSocketAddress());*/
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
The output I get is this for the server.
Waiting for client on port 6066...
Just connected to /127.0.0.1:52349
--65536
i = 4b1 = [B@48270664
Waiting for client on port 6066...
Socket timed out!
There two things wrong. The first is that the bytearray is not coming entirely to the server. And secondly the server is calling thread twice.
Any input will be helpful. Please let me know if anyone finds a problem!
SocketTimeoutdue to the timeout on theServerSocket, which caused the 'Socket timed out!' condition.