wood burning stoves*
The moose likes Sockets and Internet Protocols and the fly likes How to send a message back from Server to Client? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "How to send a message back from Server to Client?" Watch "How to send a message back from Server to Client?" New topic
Author

How to send a message back from Server to Client?

Sean Hetfield
Ranch Hand

Joined: Dec 01, 2003
Posts: 83
I have three file as shown which are Client, SocketClient and Server.
What the Client does, is just to send a IP address and an Iteration Variable for my personal useage, to the SocketClient.
So my main components are SocketClient and Server, and as you see the code, I can send a message form SocketClient to Server, but i can not send the same message back to server(Actually I have tried, but I have got Exceptions).
So please let e know any solution that you can think of.

Client.java
-------------------------------------------------------------------------
import java.io.*;

public class Client
{
public static void main (String[] args)
{
SocketClient sc = new SocketClient();

//for console

if (args.length == 2) sc.sendPara(args[0],Integer.parseInt(args[1]));// remote IP address, and iteration numbers
else
if (args.length == 1) sc.sendPara("localhost", Integer.parseInt(args[0]));//local host and iteration numbers
else
System.out.println("Invalid arguments...");



SocketClient.java
---------------------------------------------------------------------------
import java.util.Date;
import java.sql.*;
import java.net.*;
import java.io.*;

public class SocketClient
{
void sendPara(String ipAddress, int iterNum)
{
int port = 8888;//the address of the remote server
String ServerIP = ipAddress;
long startTime = 0, endTime = 0, latencyShot = 0, latencyLong = 0;

try{
InetAddress address = InetAddress.getByName(ServerIP);//get the server by IP address

Socket socket = new Socket(address,port);//initiate a socket object

OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
PrintWriter pw = new PrintWriter(osw);//create a PrintWriter object for output

InputStream sIn = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(sIn);
BufferedReader br = new BufferedReader(isr);//create a BufferReader object for input

pw.print("This is written from Client to Server.");
pw.flush();


socket.close();

}catch(IOException e){
System.err.print(e);
}
}

}//end of the class



Server.java
---------------------------------------------------------------------------
import java.net.*;
import java.io.*;
import java.sql.*;
import java.math.*;

public class Server implements Runnable
{//routine - a socket server
int ID;
Socket socket;

public static void main(String[] arg)
{
int port = 8888;
int count = 0;

try{
ServerSocket s = new ServerSocket(port,count);
System.out.println("Waiting on port " + port);

while(true)
{
Socket socket = s.accept();
System.out.println("Connet! ID=" + ++count);
Server server = new Server(socket,count);
System.out.println("before creat thread");
Thread thread = new Thread(server);
System.out.println("before thread");
thread.start();
}
}catch(Exception e){
System.err.println("Server error");
System.err.println(e);
}
}//end of the main()

Server(Socket socket, int ID)
{
this.socket = socket;
this.ID = ID;
}

public void run()
{
System.out.println("thread start");
try
{
InputStream sIn = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(sIn);
BufferedReader br = new BufferedReader(isr);

OutputStream sOut = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(sOut);
PrintWriter pw = new PrintWriter(osw);//create a PrintWriter object for output

String inString = br.readLine();

System.out.println("inString: " + inString);

while (inString != null)
{
pw.println(inString);
pw.flush();

inString = br.readLine();
}

}catch (Exception e){
System.err.println(e);
}finally{// Close all objects
try
{
socket.close();
}catch(IOException e){
System.out.println(e);
}
System.out.println("Disconnect! ID=" + ID);
}

}//end of the thread run()

}//end of the class
Sean Hetfield
Ranch Hand

Joined: Dec 01, 2003
Posts: 83
Any idea?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24166
    
  30

You're getting an exception when the server tries to send a reply because as soon as the client sends its initial message, it calls "close()" to close the socket and exits. Obviously, if the server's going to send something back to the client, the client has to be there waiting for it, right?

You've already set up a BufferedReader on the client end; the client just has to call br.readLine() after the print/flush.

Now, another problem that will crop up is that the server is calling readLine() to read a line, but the client isn't sending a newline character, so if the socket stays open, the server won't see the end-of-file to terminate the read. The client needs to use "println()" rather than "print()".


[Jess in Action][AskingGoodQuestions]
Sean Hetfield
Ranch Hand

Joined: Dec 01, 2003
Posts: 83
First of all When I use println() instead of print() in SocketClient.java, I get
java.net.SocketException: Software caused connection abort: recv failed

and also What I was doing before is the same that you suggested (the client just has to call br.readLine()after the print/flush.) but what happens is that Client side is kind of freezing, and Server was not writing the message I was sending to it and when I close the Clinet Console, in Server I got java.net.SocketException: Connection reset.

I appreciate a fast answer, because it's a kid of urgent matter.
Sean Hetfield
Ranch Hand

Joined: Dec 01, 2003
Posts: 83
I just wanted to add one more comment that I just found out and that is:
if I don't flush the data in SocketClient and I try to read data from Server, I can do it. So the problem remains that where to locate the flush() to be able to write and read at the same time.
Sean Hetfield
Ranch Hand

Joined: Dec 01, 2003
Posts: 83
My problem is solved now
But the only combination is working is: Using println() and flush() in SocketClinet.java and Using println() without flush() in Server.java.
Any other combination will lead to exception.
If you have any comment regading that please let me know.

Thanks
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: How to send a message back from Server to Client?
 
Similar Threads
Help with sockets
A good, simple tutorial for making sockets work over the Internet.
Can't catch Window Close event when trying SocketServer trying to accept connections
How can I specify size of a String?
Mimic Browser Httprequests & posts