• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to send a message back from Server to Client?

 
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 83
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Any idea?
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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()".
 
Sean Hetfield
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 83
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 83
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
Lookout! Runaway whale! Hide behind this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic