Server not reading data - java

I had modified the Java Socket Tutorials code to allow the client to send a string array and the server passes the array back with the strings in the array changed. It works fine.
Now I am trying to create a server class that behaves as a server component. The component basically only receives data from the client and prints the client data. However, the server accepts the connection but does not reading. Hence, to see what was happening, I tried to just run a server socket from main. Even that is not working. I am not sure why the tutorial code works but not when I do the exact thing in my code. I do not understand the reason for such peculiar behavior.
Following is the Java Tutorial Code for Server
import java.net.*;
import java.io.*;
public class Server {
public static void main(String[] args) throws IOException {
int portNumber = Integer.parseInt(args[0]);
try
(
ServerSocket serverSocket =
new ServerSocket(Integer.parseInt(args[0]));
Socket clientSocket = serverSocket.accept();
ObjectInputStream objIn = new ObjectInputStream(clientSocket.getInputStream());
ObjectOutputStream objOut = new ObjectOutputStream(clientSocket.getOutputStream());
) {
String str[][] = (String [][])objIn.readObject();
if(str != null)
{ for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
System.out.println(str[i][j]);
for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
str[i][j] ="Success";
objOut.writeObject(str);
}
} catch (IOException | ClassNotFoundException ecp) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(ecp.getMessage());
}
}
}
The following is the client from Java Tutorial
public class EchoClient {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println(
"Usage: java EchoClient <host name> <port number>");
System.exit(1);
}
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
try (
Socket echoSocket = new Socket(hostName,portNumber);
ObjectOutputStream objOut = new ObjectOutputStream(echoSocket.getOutputStream());
ObjectInputStream objIn = new ObjectInputStream(echoSocket.getInputStream());
PrintWriter out =
new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
BufferedReader stdIn =
new BufferedReader(
new InputStreamReader(System.in))
) {
String str[][] = new String[8][8];
for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
str[i][j] = "Test";
objOut.writeObject(str);
System.out.println("String array sent");
str = (String[][])objIn.readObject();
for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
System.out.println(str[i][j]);
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + hostName);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
hostName);
System.exit(1);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now the following is my simple server attempt which does not read when EchoClient sends data. It connects but not read.
import java.net.*;
import java.io.*;
public class Server
{
public static void main (String[] args)
{
try {
ServerSocket serv = new ServerSocket(8000);
Socket client = serv.accept();
ObjectInputStream objin = new ObjectInputStream(client.getInputStream());
String[][] str = (String[][]) objin.readObject();
for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
str[i][j] ="Success";
System.out.println(str[0][0]);
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Please let me know where I am going wrong. Note the Java tutorial classes EchoServer and EchoClient work as expected. But I am unable to replicate it on my own. The Server class accepts EchoClient but does not read.
EDIT:Following is my fixed attempt. This works as intended.
Server class:
import java.net.*;
import java.io.*;
public class Server
{
ServerSocket serverSocket;
Socket clientSocket;
String hostname;
int portNo = 8000;
String clientData;
int count = 0;
public Server()
{
try {
serverSocket = new ServerSocket(portNo);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void startReceiving()
{
try {
if(clientSocket == null)
{ clientSocket = serverSocket.accept();
System.out.println("Client Connected");
}
ObjectInputStream objIn = new ObjectInputStream(clientSocket.getInputStream());
//String strtemp[][];
String data;
while(true)
{
if((data = (String)objIn.readObject()) != null)
{
this.clientData = data;
System.out.println(this.clientData);
break;
}
/*if((strtemp = (String[][]) objIn.readObject())!= null)
{
str = strtemp;
System.out.println("received data");
for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
System.out.println(str[i][j]);
}
else
System.out.println("no data received");*/
}
sendData();
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
try {
clientSocket.close();
clientSocket = null;
startReceiving();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
public void sendData()
{
/*for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
str[i][j] ="Success";*/
this.clientData = "client request response" + count;
count++;
ObjectOutputStream objOut;
try {
objOut = new ObjectOutputStream(clientSocket.getOutputStream());
objOut.writeObject(this.clientData);
objOut.flush();
startReceiving();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main (String[] args)
{
Server server = new Server();
server.startReceiving();
}
}
Following is the client:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class TestClient
{
Socket connection;
String hostname = "localhost";
int portNo = 8000;
String incomingData;
int count;
public TestClient()
{
try {
connection = new Socket(hostname,portNo);
count = 0;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void receiveData()
{
ObjectInputStream in;
try {
in = new ObjectInputStream(this.connection.getInputStream());
String serverMessage;
while (true)
{
if((serverMessage = (String)in.readObject()) != null)
{
System.out.println(serverMessage);
break;
}
}
if(count < 5)
sendData();
else
{
in.close();
this.connection.close();
}
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//
}
public void sendData()
{
try {
ObjectOutputStream out = new ObjectOutputStream(connection.getOutputStream());
out.writeObject("Client request" + count);
out.flush();
count++;
receiveData();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[])
{
TestClient testClient = new TestClient();
testClient.sendData();
}
}

Your client creates an ObjectInputStream but the server doesn't create a corresponding ObjectOutputStream, so the client blocks waiting for the object stream header that is never sent.
Also you should get rid of all the Readers and Writers. You can't combine different kinds of reader/writer/stream over the same socket.
Also your server doesn't close the socket properly.
Also the error message 'couldn't get I/O for ...' is meaningless. I know it comes from the Java Tutorial, and I complained to them about it decades ago, but you should never make up your own error message and throw away the one that comes with the exception like this.

You did not understand properly how this application is designed.
You removed the part where you send str[i][j] but still set it to success in the loop, this is illogical. At first run, the server will read nothing, therefore it will never set any values to the array and this is why System.out.println(str[0][0]) print nothing.
You have to understand that in the example from the tutorial, the first loop read what is received
for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
System.out.println(str[i][j]);
Then the second loop simply write success everywhere and re-send the data to the EchoClient.
for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
str[i][j] ="Success";
objOut.writeObject(str);
Using this main
public static void main (String[] args)
{
int portNumber = 8000;
try {
ServerSocket serv = new ServerSocket(portNumber);
Socket client = serv.accept();
ObjectInputStream objin = new ObjectInputStream(client.getInputStream());
ObjectOutputStream objOut = new ObjectOutputStream(client.getOutputStream());
String str[][] = (String[][]) objin.readObject();
if(str != null)
{
for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
System.out.println(str[i][j]);
for(int i = 0; i<str.length;i++)
for(int j = 0; j<str[i].length;j++)
str[i][j] ="Success";
objOut.writeObject(str);
}
System.out.println(str[0][0]);
} catch (IOException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Which is the one you used, but where I re-added the second loop and writing, will print on both Client and Server.
You should also consider handling the Socket termination in a finally block to make sure it is closed whatever happen to your program.
try
{
...
}
catch(IOEXception e)
{
...
}
finally
{
if(socket != null)
socket.close();
}
Make sure to declare the socket outside of the try scope so it is accessible in the finally.

Related

Network communication isnĀ“t working

I made a little game. Now i want to get the highscore from my Server. The code on the client:
private int getOnlineHighscore() {
int highscore = 0;
try {
socket = new Socket("localhost", 444);
input = socket.getInputStream();
System.out.println(input);
highscore = input.read();
input.close();
socket.close();
input = null;
socket = null;
} catch (Exception e) {
System.out.println("Verbindung fehlgeschlagen!");
}
System.out.println(highscore);
return highscore;
}
And on the Server:
import java.io.*;
import java.net.*;
public class ReadServer extends Thread {
private Socket socket;
public ReadServer(Socket socket) {
super();
this.socket = socket;
}
public void run() {
try {
System.out.println(socket.getInetAddress());
String result = "";
try (BufferedReader br = new BufferedReader(
new FileReader(System.getProperty("user.home") + "/AppData/Roaming/GameServer/.sg"))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
System.out.println("2");
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
System.out.println("3");
result = sb.toString();
System.out.println("3.5");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("4");
socket.getOutputStream().write(Integer.parseInt(result));
System.out.println(result);
} catch (Exception e) {
}
try {
socket.close();
} catch (Exception e) {
}
}
public static void main(String[] Args) {
Socket socket = null;
ServerSocket server = null;
try {
server = new ServerSocket(444);
while (true) {
socket = server.accept();
new ReadServer(socket).start();
}
} catch (Exception e) {
}
try {
server.close();
} catch (Exception e) {
}
}
}
If I run it, the client function returns:
-1
The server writes in the console(not important I think):
/127.0.0.1
2
3
3.5
4
How to solve the problem? I want to send an int stored on my Server to a client.
-Jakob
-1 is returned by read() to specify end of stream , make sure data to be read is being returned .
What is the highscore stored in the file? I believe the file is empty and it fails on parsing the integer but as your catch block is empty, you don't see the exception. Put printStacktrace or rethrow.
Another problem is that OutputStream sends only bytes and therefore write method sends only low 8 bits. To send int wrap the stream with DataOutputStream and DataInputStream on the client side.

java.net.SocketException: Connection reset error

I am using socket in Java.
Client send a name and phone number.
then sever get client data and encrypt it.
however problem accrue.
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:168)
at java.io.DataInputStream.readFully(DataInputStream.java:178)
at java.io.DataInputStream.readUTF(DataInputStream.java:592)
at java.io.DataInputStream.readUTF(DataInputStream.java:547)
at chat.QrcodeServer.dataEnc(QrcodeServer.java:45)
at chat.QrcodeServer.main(QrcodeServer.java:25)
Server:
import java.io.*;
import java.net.*;
public class QrcodeServer{
public static void main (String[] args){
ServerSocket ss = null;
Socket client = null;
int port = 10000;
try {
ss = new ServerSocket(port);
System.out.println("Service is started in "+ port);
}catch (IOException ee){
ee.printStackTrace();
}
try{
while (true){
client = ss.accept();
System.out.println("Client Info:" + client);
dataEnc(client);
}
}catch(IOException ee){
ee.printStackTrace();
}
}
public static void dataEnc(Socket client){
// Get an input file handle from the socket and read the input
InputStream cin=null;
String data=null;
String password=null;
try {
//get client Data Stream
cin = client.getInputStream();
DataInputStream dis = new DataInputStream(cin);
//get data
data = new String (dis.readUTF());
password = new String(dis.readUTF());
System.out.println(data);
System.out.println(password);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//To make password hash
String passwordTemp = Crypto.getPassword(password);
try {
//encrypt data through passwordTemp
byte[] cipher = Crypto.encrypt(data,passwordTemp);
//printout the cipher data
System.out.print("cipher: ");
for(int i=0; i<cipher.length;i++){
System.out.print(Integer.toHexString(0xff&cipher[i])+" ");
}
System.out.println();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Client:
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
Socket server = null;
String ip = "ip addr";
int port = 10000;
try{
server = new Socket(ip, port);
System.out.println("server: "+ip + "and port is "+ port );
sendInfo(server);
}catch(IOException e){
e.printStackTrace();
}
}
public static void sendInfo (Socket soc){
// Get a communication stream associated with the socket
OutputStream cout;
try {
cout = soc.getOutputStream();
DataOutputStream dos = new DataOutputStream (cout);
String name="kevin";
String phone="123456780";
String password="password";
String data = name+phone;
// Send a data
dos.writeUTF(data);
dos.writeUTF(password);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
It works in localhost and local interior network.
but problem above accrue when client connected from internet.
What might be the problem?

Client server programming in java with options to user

My task is to display three options to the user 1)connect to server 2)post data 3)disconnect. I am having trouble in sending the file to the server. "The file needs to be sent from client to server". I am new to socket programming and however I try the connection is being reset while I try to send the file to server.
server
import java.net.*;
import java.util.Scanner;
import java.io.*;
public class Server extends Thread {
private ServerSocket serverSocket;
public Server(int port) throws IOException {
serverSocket = new ServerSocket(port);
}
public void run() {
boolean flag = true;
while (flag) {
try {
System.out.println("Waiting for client on port "
+ serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
Scanner reader = new Scanner(server.getInputStream());
File file = new File("compile.txt");
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(
file));
while (reader.hasNextLine()) {
String str = reader.next();
fileWriter.write(str);
System.out.println("" + str);
}
} catch (Exception e) {
e.printStackTrace();
break;
}
}
}
public static void main(String[] args) {
int port = 4444;
try {
Thread t = new Server(port);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
client
import java.net.*;
import java.util.Scanner;
import java.io.*;
public class Client {
public static void main(String[] args) {
Socket client = null;
boolean flag = true;
while (flag) {
System.out
.println("Please enter your choice\n1.Connect to Server\n2.Post Data\n3.Disconnect from Server");
Scanner userChoice = new Scanner(System.in);
int choice = userChoice.nextInt();
String serverName = "localhost";
int port = 4444;
if (choice == 1) {
try {
System.out.println("Connecting to " + serverName
+ " on port " + port);
client = new Socket(serverName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
} catch (IOException e) {
e.printStackTrace();
}
} else if (choice == 2) {
System.out.println("enter path of file to be compiled");
Scanner pathReader = new Scanner(System.in);
String path = pathReader.next();
pathReader.close();
String line;
try {
BufferedReader br = new BufferedReader(new FileReader(path));
while ((line = br.readLine()) != null) {
PrintWriter writer = new PrintWriter(
client.getOutputStream(), true);
writer.write(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
client.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (choice == 3) {
try {
client.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else
System.out.println("enter a valid input");
}
}
}
First of all client-server socket connections and applications are pretty complicated. I'd recommend reading:
http://www.oracle.com/technetwork/java/socket-140484.html#sockets
couple of things to consider:
make sure there is nothing running on the socket.
make sure that the server is listening
You are running the server on one thread, so if it finishes at all then it won't restart
You are not closing the fileWriter once you have finished writing -
please post your output/any stacktraces you have

BufferedReader from server does not work

In this code I can correctly receive a request using BufferedReader inClient, created on the client socket.
Then I send the request to the server and I see the server gets it.
But then, when I try to read the reply from the server (using BufferedReader inServer on the socket of the server), it always ends in IOException: Impossible read from server.
I am referring to the block ################
Do you know any possible reasons?
import java.io.*;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class ProxyMain {
public static void main(String argv[]) {
int proxyPort = 55554;
String proxyAddr = "127.0.0.1";
ServerSocket proxySocket = null;
try {
proxySocket = new ServerSocket(proxyPort, 50, InetAddress.getByName("127.0.0.1"));
}
catch (Exception e) {
System.err.println("Impossible to create socket server!");
System.out.flush();
System.exit(1);
}
System.out.printf("Proxy active on port: %d and on address %s\n", proxyPort, proxySocket.getInetAddress());
System.out.println();
while (true) {
Socket client = null;
Socket sockServ = null;
BufferedReader inClient = null;
PrintWriter outClient = null;
BufferedReader inServer = null;
PrintWriter outServer = null;
String request = new String();
String tmp = new String();
String reply = new String();
String tmpReply = new String();
try {
client = proxySocket.accept();
System.out.println("Connected to: ");
System.out.println(client.getInetAddress().toString());
System.out.printf("On port %d\n", client.getPort());
System.out.println();
inClient = new BufferedReader(new InputStreamReader(client.getInputStream()));
outClient = new PrintWriter(client.getOutputStream(), true);
}
/*catch (IOException e) {
System.err.println("Couldn't get I/O for connection accepted");
System.exit(1);
}*/
catch (Exception e) {
System.out.println("Error occurred!");
System.exit(1);
}
System.out.println("Received request:");
try{
for (int i = 0; i<2; i++) {
tmp = inClient.readLine();
request = request + tmp;
}
inClient.close();
}
catch (IOException ioe) {
System.err.println("Impossible to read mhttp request!");
System.exit(1);
}
System.out.println(request);
System.out.println();
try {
sockServ = new Socket("127.0.0.1", 55555);
outServer = new PrintWriter(sockServ.getOutputStream(), true);
inServer = new BufferedReader(new InputStreamReader(sockServ.getInputStream()));
}
catch (UnknownHostException e) {
System.err.println("Don't know about host: 127.0.0.1:55555");
System.exit(1);
}
catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: 127.0.0.1:55555");
System.exit(1);
}
outServer.println(request);
outServer.close();
try {
#################################################
while ((tmpReply = inServer.readLine()) != null) {
System.out.println(tmpReply);
reply = reply + tmpReply;
}
inServer.close();
sockServ.close();
}
catch (IOException ioe) {
System.err.println("Impossible to read from server!");
System.exit(1);
}
outClient.println(reply);
outClient.close();
try {
client.close();
}
catch (IOException ioe) {
System.err.printf("Impossible to close connection with %s:%d\n", client.getInetAddress().toString(), client.getPort());
}
}
}
}
UPDATE:
It seems that if I do:
boolean res = inServer.ready();
it always return false.
So Server is not ready to send the reply but this is strange...with my Project in C e Python it worked immediately. Why should java be different?
When you close outServer, you close the underlying socket. if you just want to close the output and keep the input open, you need to use Socket.shutdownOutput(). note, you have the same problem when you close inClient.
This works, maybe you can get some ideas from it...
ChatServer - broadcasts to all connected clients
In one command prompt: java ChartServer
In another: java ChatClient localhost (or the ip address of where the server is running)
And another: java ChatClient localhost (or the ip address of where the server is running)
Start chatting in the client windows.
Server like this...
// xagyg wrote this, but you can copy it
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
public static List list = new ArrayList();
public static void main(String[] args) throws Exception {
ServerSocket svr = new ServerSocket(4444);
System.out.println("Chat Server started!");
while (true) {
try {
Socket s = svr.accept();
synchronized(list) {
list.add(s);
}
new Handler(s, list).start();
}
catch (IOException e) {
// print out the error, but continue!
System.err.println(e);
}
}
}
}
class Handler extends Thread {
private Socket s;
private String ipaddress;
private List list;
Handler (Socket s, List list) throws Exception {
this.s = s;
ipaddress = s.getInetAddress().toString();
this.list = list;
}
public void run () {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
String message;
//MyDialog x = (MyDialog)map.get(ipaddress.substring(1));
while ((message = reader.readLine()) != null) {
if (message.equals("quit")) {
synchronized(list) {
list.remove(s);
}
break;
}
synchronized(list) {
for (Object object: list) {
Socket socket = (Socket)object;
if (socket==s) continue;
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.println(ipaddress + ": " + message);
writer.flush();
}
}
}
try { reader.close(); } catch (Exception e) {}
}
catch (Exception e) {
System.err.println(e);
}
}
}
Client like this ...
// xagyg wrote this, but you can copy it
import java.util.*;
import java.io.*;
import java.net.*;
public class ChatClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket(args[0], 4444);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter out = new PrintWriter(s.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String message;
new SocketReader(in).start();
while ((message = reader.readLine())!=null) {
out.println(message);
out.flush();
if (message.equals("quit")) break;
}
in.close();
out.close();
}
}
class SocketReader extends Thread {
BufferedReader in;
public SocketReader(BufferedReader in) {
this.in = in;
}
public void run() {
String message;
try {
while ((message = in.readLine())!=null) {
System.out.println(message);
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
}

How to Run Server Client code using Socket Programming in Java Eclipse?

Client code:
import java.io.*;
import java.net.*;
public class SimpleClient {
public static void main(String[] args) throws IOException {
Socket clientSocket = null;
try {
clientSocket = new Socket(args[0], 4442);
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + args[0] + ".");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " +
"the connection to: " + args[0] + "");
System.exit(1);
}
BufferedInputStream in;
BufferedOutputStream out;
try {
in = new BufferedInputStream(clientSocket.getInputStream());
out = new BufferedOutputStream(clientSocket.getOutputStream());
} catch (IOException e) {
System.out.println(e.toString());
return;
}
byte[] m_txt = args[1].getBytes();
out.write(m_txt, 0, m_txt.length);
out.flush();
byte[] m_rcv = new byte[m_txt.length];
int n = in.read(m_rcv, 0, m_rcv.length);
if (n != m_rcv.length) {
System.out.println("Some data are lost ...");
}
System.out.println(new String(m_rcv));
out.close();
in.close();
clientSocket.close();
}
}
Server:
import java.io.*;
import java.net.*;
public class SimpleServer {
public static void main(String[] args) throws IOException {
boolean listening = true;
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4442);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
while(listening) {
Socket clientSocket = serverSocket.accept();
(new SimpleConHandler(clientSocket)).start();
}
serverSocket.close();
}
}
Connection Handler:
import java.io.*;
import java.net.*;
public class SimpleConHandler extends Thread
{
private Socket clientSocket;
public SimpleConHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
}
public void run() {
BufferedInputStream in;
BufferedOutputStream out;
try {
in = new BufferedInputStream(clientSocket.getInputStream());
out = new BufferedOutputStream(clientSocket.getOutputStream());
} catch (IOException e) {
System.out.println(e.toString());
return;
}
try {
byte[] msg = new byte[4096];
int bytesRead = 0;
int n;
while((n = in.read(msg, bytesRead, 256)) != -1) {
bytesRead += n;
if (bytesRead == 4096) {
break;
}
if (in.available() == 0) {
break;
}
}
for(int i=bytesRead; i>0; i--) {
out.write(msg[i-1]);
}
out.flush();
} catch(IOException e1) {
System.out.println(e1.toString());
}
try {
out.close();
in.close();
clientSocket.close();
} catch ( IOException e2 ) {;}
}
}
First i RUN Server, but when i try to RUN Client, the error which i am getting is:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at SimpleClient.main(SimpleClient.java:11)
May be i have to use different consoles to run both the Server and the Client? If so, then please tell me the way. i am using Java Eclipse 1.6 SE.
clientSocket = new Socket(args[0], 4442);
Your program needs a command line argument:
java your.Program <ip>

Categories