TCP client and server, cmd prompt using objectstreams - java

I have one client file clientRPC.java and server file serverRPC.java. Both communicate using TCP protocol and use objectinput and output stream to transfer data.
my client file:
public class clientRPC {
public static void main(String args[]) {
Socket s = null;
try {
int serverPort = 8888;
s = new Socket("localhost", serverPort);// server name is local host
//initializing input and output streams object and referencing them to get input and output
ObjectInputStream in = null;
ObjectOutputStream out = null;
out = new ObjectOutputStream(s.getOutputStream());
in = new ObjectInputStream(s.getInputStream());
MathsTutor mt = new MathsTutor();
out.writeObject(mt);
out.flush();
System.out.println("Welcome to Maths Tutor Service. The available maths exercises are:\n"
+ "Addition: Enter 'A' or 'a'\n"
+ "Subtraction: Enter 'S' or 's'\n"
+ "Multiplication: Enter 'M' or 'm'\n"
+ "Division: Enter 'D' or 'd'\n"
+ "Enter 'Q' or 'q' to quit");
//System.out.println();
MathsTutor mt1 = (MathsTutor) in.readObject();
String response = in.readUTF();
System.out.println(response);
} catch (UnknownHostException e) {
System.out.println("Socket:" + e.getMessage());
} catch (EOFException e) {
System.out.println("EOF:" + e.getMessage());
} catch (IOException e) {
System.out.println("readline:" + e.getMessage());
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} finally {
if (s != null) {
try {
s.close();
} catch (IOException e) {
System.out.println("close:" + e.getMessage());
}
}
}
}
}
and my server file :
public class serverRPC extends Thread {
String request;
String response;
public static void main(String args[]) {
try {
int serverPort = 8888;
ServerSocket listen_socket = new ServerSocket(serverPort);
while (true) {
Socket clientSocket = listen_socket.accept();
Connection c = new Connection(clientSocket);
}
} catch (IOException e) {
System.out.println("Listen socket:" + e.getMessage());
}
public serverRPC(String s) {
request = s;
}
}
class Connection extends Thread {
ObjectInputStream in;
ObjectOutputStream out;
Socket clientSocket;
public Connection(Socket aClientSocket) {
try {
clientSocket = aClientSocket;
in = new ObjectInputStream(clientSocket.getInputStream());
out = new ObjectOutputStream(clientSocket.getOutputStream());
this.start();
} catch (IOException e) {
System.out.println("Connection:" + e.getMessage());
}
}
public void run() {
try {
MathsTutor mt = (MathsTutor) in.readObject();
InetAddress ip = clientSocket.getInetAddress();
System.out.println("The Received Message from Client at address:/" + ip.getHostAddress());
System.out.println("====================================");
MathsTutor mt1 = new MathsTutor();
out.writeObject(mt1);
while(true) {
// Read from input
String command = in.readUTF();
System.out.println(command);
}
//System.out.println();
} catch (EOFException e) {
System.out.println("EOF:" + e.getMessage());
} catch (IOException e) {
System.out.println("readline:" + e.getMessage());
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {/*close failed*/
}
}
}
}
The problem is when I run server and then client on cmd, the client side displays the welcome msg and puts cursor on another line for user input but, I can't type anything, the cursor just blinks... I know this might be simple but it has taken already 3 hours for me and I'm stuck in the same thing.
The cursor marked with red keeps blinking but doesn't let me type anything.

You're writing an object with writeObject() and trying to read it with readUTF(). Illogical.
objects written with writeObject() must be read with readObject().
strings written with writeUTF() must be read with readUTF().
primitives written with writeXXX() must be read with readXXX(), for most values of X.

Related

Java how to read with ObjectInputStream

It's my first time working with sockets, in order to get a better understanding of what's going on I decided to build a client server chat application which can support several users.
At first, I used DataInputStream / DataOutputStream to communicate and everything works well. But I would like to switch to an ObjectStream and that's where the problem occurs. Once I replace all the DataInputStream / DataOutputStream by ObjectInputStream / ObjectOutputStream, I'm no longer able to print the retrieved data.
This is the code that I used before, which works (DataStream) :
SERVER:
try {
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("HI FROM SERVER");
while (!socket.isClosed()) {
try {
if (in.available() > 0) {
String input = in.readUTF();
for (ClientThread thatClient : server.getClients()){
DataOutputStream outputParticularClient = new DataOutputStream(thatClient.getSocket().getOutputStream());
outputParticularClient.writeUTF(input + " GOT FROM SERVER");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
CLIENT:
try {
socket = new Socket("localhost", portNumber);
DataInputStream in = new DataInputStream(socket.getInputStream());
new Thread(()->{
while(!socket.isClosed()){
try {
if (in.available() > 0){
String input = in.readUTF();
System.out.println(getUserName() + " > " + input);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
And this is how I tried to perform the same idea with ObjectStream :
SERVER:
try {
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
while (!socket.isClosed()) {
try {
if (in.available() > 0) {
Message input;
try {
input = (Message)in.readObject();
if (input.equals(null)){
System.err.println("SERVER RETRIEVED NULL OBJECT");
}
for (ClientThread thatClient : server.getClients()){
ObjectOutputStream outputParticularClient = new ObjectOutputStream(thatClient.getSocket().getOutputStream());
outputParticularClient.writeObject(input);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
CLIENT:
try {
socket = new Socket(getHost(), portNumber);
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
new Thread(()->{
while(!socket.isClosed()){
try {
if (in.available() > 0){
Message input = null;
try {
input = (Message)in.readObject();
if (input.equals(null)){
System.err.println("CLIENT RETRIEVED NULL OBJECT");
}
System.out.println("CLIENT " + input.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
I feel like it has something to do with this if statement if (in.available() > 0) but I cannot say precisely what's going on.
available() doesn't do what you may think it does and it is almost never useful in production code (and that's particularly true for ObjectInputStream). The reason you don't receive any data is in fact that in.available() always returns 0 as you already suspected.
As noted in the comments, the StreamCorruptedException is caused by writing to an existing ObjectInputStream that has already been written to using another instance of ObjectOutputStream. Cf. the answer StreamCorruptedException: invalid type code: AC for further explanation.
Here is some quick & dirty example code that has a server echoing the messages from two clients. It's not clean but it may give you an idea how to approach your problem:
public class SO56493162 {
private static final class Message implements Serializable {
private static final long serialVersionUID = 1L;
private static int cnt = 0;
private final int id;
public Message(int id) {
++cnt;
this.id = id;
}
public String toString() {
return "Msg from " + id + " : " + cnt;
}
}
private static final class Client implements Runnable {
private InetSocketAddress addr = null;
private int id = -1;
Client(InetSocketAddress addr, int id) {
this.addr = addr;
this.id = id;
}
public void run() {
int timeout = 3000;
Socket s = null;
try {
s = new Socket();
s.connect(addr, timeout);
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
System.out.println("Client " + id + " connected");
while (true) {
Thread.sleep(new Random().nextInt(2000));
Message hello = new Message(id);
oos.writeObject(hello);
oos.flush();
Message reply = (Message) ois.readObject();
System.out.println("Reply: " + reply.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (Exception ignore) {
}
}
}
}
private static final class Server implements Runnable {
private ServerSocket sock = null;
Server(ServerSocket sock) throws IOException {
this.sock = sock;
}
public void run() {
System.out.println("starting server");
try {
while (true) {
final Socket client = sock.accept();
System.out.println("connection accepted");
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
while (!client.isClosed()) {
try {
Message input = (Message) ois.readObject();
oos.writeObject(input);
oos.flush();
} catch (EOFException eof) {
System.err.println("EOF!");
client.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.setDaemon(true);
t.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) throws IOException, InterruptedException {
final int port = 9876;
Thread ts = new Thread(new Runnable() {
#Override
public void run() {
try {
new Server(new ServerSocket(port)).run();
} catch (Exception e) {
e.printStackTrace();
}
}
});
ts.setDaemon(true);
ts.start();
InetSocketAddress addr = new InetSocketAddress("localhost", port);
for (int i = 0; i < 2; ++i) {
Client cl = new Client(addr, i);
Thread tc = new Thread(cl);
tc.setDaemon(true);
tc.start();
}
Thread.sleep(10000);
System.err.println("done");
}
}

How to send double from client to server and back to client using I/O

I cannot use scanners or printwriters
I have a client, and a server.
i run the server and the output is,
Creating Server Socket 5095 . . .
SUCCESS!!!
in while loop
Waiting for connection.
then i run the client and the output is,
Creating Client Socket
SUCCESS!!!
initializing variables
variables flushed
initializing input
java.io.EOFException
at java.io.DataInputStream.readFully(Unknown Source)
at java.io.DataInputStream.readLong(Unknown Source)
at java.io.DataInputStream.readDouble(Unknown Source)
at Client.runClient(Client.java:38)
at Client.main(Client.java:51)
I would like to initialize some doubles in the client, and send them to the server, where they will be parsed and manipulated, with the result then being sent back to the client.
The client fails with an EOFException and the server fails with a ClassCastException
What Am I doing wrong?
import java.io.*;
import java.net.*;
import java.util.*;
public class Client {
static void pStr(String p) {
System.out.println(p);
}
static void runClient() {
Socket client;
DataOutputStream output;
DataInputStream input;
try {
pStr("Creating Client Socket ");
client = new Socket("127.0.0.1", 5095);
pStr("SUCCESS!!!");
input = new DataInputStream(client.getInputStream());
output = new DataOutputStream(client.getOutputStream());
System.out.println("initializing variables");
double arg1 = 5;
output.writeDouble(arg1);
output.flush();
double arg2 = 3;
output.writeDouble(arg2);
output.flush();
System.out.println("variables flushed");
System.out.println("initializing input");
// error occurs at next line
double ans = input.readDouble();
System.out.println("input has been read");
System.out.println(ans);
input.close();
output.close();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// this is second class file
public static void main(String args[]) {
Client.runClient();
}
}
public class SimpleServer {
static void pStr(String p) {
System.out.println(p);
}
static void runServer() {
ServerSocket server;
try {
// Create a ServerSocket.
pStr("Creating Server Socket " + 5095 + " . . . ");
server = new ServerSocket(5095);
pStr("SUCCESS!!!");
while (true) {
System.out.println("in while loop");
Socket connection;
DataOutputStream output = null;
DataInputStream input = null;
pStr("Waiting for connection.");
connection = server.accept();
pStr("Done");
System.out.println("entering try");
try {
// Get input and output streams.
input = (DataInputStream) connection.getInputStream();
output = (DataOutputStream) connection.getOutputStream();
String ansStr;
double arg1, arg2;
try {
System.out.println("int try block");
arg1 = input.readDouble();
arg2 = input.readDouble();
ansStr = "" + arg1 + "," + arg2;
System.out.println(ansStr);
output.writeDouble(arg1);
output.writeDouble(arg2);
} catch (Exception e) {
ansStr = e.getMessage();
}
output.flush();
} catch (Exception e) {
pStr("Error in Protocol: " + e.getMessage());
} finally {
try {
input.close();
} catch (Exception e) {
}
try {
output.close();
} catch (Exception e) {
}
try {
connection.close();
} catch (Exception e) {
}
}
}
} catch (Exception e) {
pStr("Error making ServerSocket");
}
}
public static void main(String args[]) {
runServer();
}
}
Your server code is crashing with a ClassCastException which you have unaccountably failed to mention. The connection is therefore being closed without any data being sent, hence the client-side exception.
You cannot get a DataInputStream or DataOutputStream from a socket just by casting. You have to use the same process you're using in the client.

Java, Socket : Send several object of an arrayList one by one, the objectInputStream does not read all of them

Hello everybody and thanks in advance to those who will read that :
I'm trying to send an ArrayList of an object "Profile" (which I made serializable) but one by one (because at the end the List will be filled by other threads but this is not the matter here).
I'm using a socket between a "clientconnexion" (which is the client) and a "clientprocessor" (which is the server). They are in different threads and at the end they will be on different computers.
When I try to do it with the following code (trying to send 50 profiles) I do receive some of them (like the 20 first, or the 30 first, sometimes even all of them or none...) but the clientconnexion stops receiving the profiles at one time...
Here is the code :
The class Profile :
public class Profile implements Serializable {
private static final long serialVersionUID = 2406276545874892098L;
public int id;
public String name;
public Profile(String name, int id){
this.id=id;
this.name=name;
}
}
The class Server (which accept the connexion and start clientprocessor thread, it only start one thread so it isn't really usefull now but it will be after) :
public class serveur {
private int port;
private String host = "0.0.0.0";
private ServerSocket server = null;
private boolean isRunning = true;
public serveur(String pHost, int pPort){
host = pHost;
port = pPort;
try {
server = new ServerSocket(port, 100, InetAddress.getByName(host));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void open(){
Thread t = new Thread(new Runnable(){
public void run(){
while(isRunning == true){
try {
Socket client = server.accept();
client.setTcpNoDelay(true);
Thread t = new Thread(new clientprocessor(client));
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
server = null;
}
}
});
t.start();
}
public void close(){
isRunning = false;
}
}
The class clientprocessor :
public class clientprocessor implements Runnable {
private Socket client;
private BufferedOutputStream bos=null;
private BufferedInputStream bis=null;
private BufferedWriter writer=null;
private BufferedReader reader=null;
private ArrayList<Profile> profilesToSend;
public clientprocessor (Socket client){
this.client = client;
this.profilesToSend=new ArrayList<>();
for (int i=1; i<51; i++){
this.profilesToSend.add(new Profile("test", i));
}
}
public synchronized Profile getProfile () {
Iterator<Profile> itr = this.profilesToSend.iterator();
if (itr.hasNext()){
Profile P = itr.next();
itr.remove();
return P;
}
return null;
}
public void run (){
try {
bos= new BufferedOutputStream (client.getOutputStream());
bis= new BufferedInputStream (client.getInputStream());
writer=new BufferedWriter(new OutputStreamWriter(bos));
reader=new BufferedReader(new InputStreamReader(bis));
ObjectOutputStream oos=new ObjectOutputStream(bos);
Profile P;
while ((P = this.getProfile())!=null) {
writer.write(0); //when the client receive a zero, e knows he will receive a profile
writer.flush();
oos.writeObject(P);
oos.flush();
System.out.println("clientprocessor : profile written (" + P.name + " " +P.id +")");
int i=reader.read(); //Waiting to receive a one to be sure that the object was received
System.out.println("clientprocessor : integer received : " +i);
}
System.out.println("--------clientprocessor : all profiles sent--------");
writer.write(1); //when the client receive a one he knows he will not receive profiles anymore
writer.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
reader.close();
bis.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
The class clientconnexion (which is supposed to be on another computer at the end) :
public class clientconnexion implements Runnable {
private Socket connexion;
private BufferedOutputStream bos=null;
private BufferedInputStream bis=null;
private BufferedWriter writer=null;
private BufferedReader reader=null;
public clientconnexion(String adress, int port) {
try {
connexion = new Socket(adress, port);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
try {
connexion.setTcpNoDelay(true);
bos= new BufferedOutputStream (connexion.getOutputStream());
bis= new BufferedInputStream (connexion.getInputStream());
writer=new BufferedWriter(new OutputStreamWriter(bos));
reader=new BufferedReader(new InputStreamReader(bis));
ObjectInputStream ois = new ObjectInputStream(bis);
int k = reader.read();
String S="clientconnexion : profiles received : ";
while (k==0){
System.out.println("clientconnexion : waiting for an object to read");
Profile P=(Profile)ois.readObject();
S = S + P.name + " " + P.id+ " ; ";
System.out.println(S);
writer.write(1);//the client sends a 1 to the server (clientprocessor)
writer.flush();
k=reader.read();
}
} catch (IOException e) {
System.out.println(e);
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
bis.close();bos.close();reader.close();writer.close();
System.out.println("clientconnexion : streams closed");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
And finally the class test which is launching all that :
public class test {
public static String adresse = "localhost";
public static int port = 9028;
public static void main(String[] args) {
serveur serveur = new serveur ("0.0.0.0",port);
System.out.println("--Test : serveur créé");
serveur.open();
System.out.println("Test : serveur ouvert");
Thread tclient1= new Thread(new clientconnexion(adresse, port));tclient1.start();
}
As you can see I tried to setTCPnoDelay but obviously it wasn't the reason of the problem.
Thanks a lot if you read that and if you can run this code and tell me if you have the same problems...
The problem is in clientprocessor class both ObjectOutputStream and BufferedWriter cannot connect to the same stream. Likewise in clientconnexion class both ObjectInputStream and BufferedReader cannot connect to the same stream. The following changes should work
clientprocessor class
try {
bos= new BufferedOutputStream (client.getOutputStream());
bis= new BufferedInputStream (client.getInputStream());
//writer=new BufferedWriter(new OutputStreamWriter(bos));
reader=new BufferedReader(new InputStreamReader(bis));
ObjectOutputStream oos=new ObjectOutputStream(bos);
Profile P;
while ((P = this.getProfile())!=null) {
//writer.write(0); //when the client receive a zero, e knows he will receive a profile
//writer.flush();
oos.write(0);
oos.flush();
oos.writeObject(P);
oos.flush();
System.out.println("clientprocessor : profile written (" + P.name + " " +P.id +")");
int i=reader.read(); //Waiting to receive a one to be sure that the object was received
System.out.println("clientprocessor : integer received : " +i);
}
System.out.println("--------clientprocessor : all profiles sent--------");
//writer.write(1); //when the client receive a one he knows he will not receive profiles anymore
//writer.flush();
oos.write(1);
oos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//writer.close();
reader.close();
bis.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
clientconnexion class
try {
connexion.setTcpNoDelay(true);
bos= new BufferedOutputStream (connexion.getOutputStream());
bis= new BufferedInputStream (connexion.getInputStream());
writer=new BufferedWriter(new OutputStreamWriter(bos));
//reader=new BufferedReader(new InputStreamReader(bis));
ObjectInputStream ois = new ObjectInputStream(bis);
int k = ois.read();
String S="clientconnexion : profiles received : ";
while (k==0){
System.out.println("clientconnexion : waiting for an object to read");
Profile P=(Profile)ois.readObject();
S = S + P.name + " " + P.id+ " ; ";
System.out.println(S);
writer.write(1);//the client sends a 1 to the server (clientprocessor)
writer.flush();
k=ois.read();
}
} catch (IOException e) {
System.out.println(e);
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
bis.close();
bos.close();
//reader.close();
writer.close();
System.out.println("clientconnexion : streams closed");
} catch (IOException e) {
e.printStackTrace();
}
}

client creates new socket object everytime the server is on

i've done a socket programming with client residing on android and server residing on the desktop ....... whenever server is down as we know client lost the connection.....so it undergoes a looping until it connects to server.......
here the problem is in the below code
tabletclient = new Socket(SERVER_IP, TAB_SERVER_PORT);
in the while loop in the case of lost connection.........but when the connection is on it again creates a new object........
can anyone please tell me how to solve this problem..........
In the client side
while(true){
try {
tabletclient = new Socket(SERVER_IP, TAB_SERVER_PORT);
tabletout = new PrintWriter(tabletclient.getOutputStream());
in = new Scanner(tabletclient.getInputStream());
try
{
if((line = in.nextLine())!=null)
{
// my task to be done
}
}catch(Exception d){
System.out.println("Connection from server has lost.........tabletclient.isConnected()----->"+tabletclient.isConnected());
}
} catch (UnknownHostException e) { System.out.println("Entered 2.........");
} catch (IOException e) { System.out.println("Entered 3.........");e.printStackTrace();
}
}
In in the Server side
:
:
private Set <Socket> TABhs=new HashSet<Socket>();
:
:
new Thread(new TABServerThread()).start(); // runs in background
:
:
:
class ServerThread implements Runnable {
private ServerSocket server;
#Override
public void run() {
try {
server = new ServerSocket(SERVER_PORT);
System.out.println("Server Start the server at port " + SERVER_PORT
+ " and waiting for clients...");
while (true) {
Socket socket = server.accept();
System.out.println("Server Accept socket connection: "
+ socket.getLocalAddress());
new Thread(new ClientHandler(socket)).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static PrintWriter out;
class ClientHandler implements Runnable {
private Socket clientSocket;
private Scanner in;
public ClientHandler(Socket clietSocket) {
this.clientSocket = clietSocket;
}
#Override
public void run() {
try {
out = new PrintWriter(clientSocket.getOutputStream());
in = new Scanner(clientSocket.getInputStream());
String line;
System.out.println("ClientHandlerThread Start communication with : "+ clientSocket.getLocalAddress());
try{
while((line = in.nextLine()) != null) {
System.out.println("ClientHandlerThread Client says: " + line);
String dat[]=line.split("#");
String query="insert into table_orders (tableno,kotno, orders,status) values('"+dat[1]+"','"+dat[0]+"','"+dat[2]+"','pending')";
try {
int i= dbGetDet.insertDetails(query);
if(i>0)
{
fillTable();
filtercomboBox();
out.print("success");
out.flush();
for(Socket so:TABhs)
{
PrintWriter ot = new PrintWriter(so.getOutputStream());
ot.println("tableallocation#"+dat[1]);
ot.flush();
}
System.out.println("SENDED 'SUCCESS' TO CLIENT");
}
} catch (Exception ex) {
Logger.getLogger(MYClientclass.class.getName()).log(Level.SEVERE, null, ex);
}
// }
}
}catch(Exception r){}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the Button click of server
String stat=status_combo.getSelectedItem().toString();
String tables=tableno_combo.getSelectedItem().toString();
String kotno=kotno_combo.getSelectedItem().toString();
if(stat.equals("Processing"))
{
try {
TABhs = new CopyOnWriteArraySet(TABhs);
int soint=1;
System.out.println("TABhs Processing--------------------->"+TABhs.size());
for(Iterator <Socket> it=TABhs.iterator();it.hasNext();)
{
Socket so=it.next();
System.out.println("SEEE SOCKET Processing"+soint+"----->"+so.isClosed());
PrintWriter ot = new PrintWriter(so.getOutputStream());
ot.println("tableupdate#"+tables+"#"+kotno+"#processing");
ot.flush();
JOptionPane.showMessageDialog(rootPane, "<html><body>Table Kot Status Changed to <b>Processing</b></body></html>");
soint++;
}
System.out.println("TABhs Processing--------------------->"+TABhs.size());
}
catch (Exception ex) {
Logger.getLogger(MYClientclass.class.getName()).log(Level.SEVERE, null, ex);
}
}
NOW EACH TIME WHEN BUTTON IS CLICKED THE OUTPUT IS AS GIVEN BELOW
FISRT CLICK
SEEE SOCKET Ready 1----->false
Server Accept socket connection: /192.168.1.74
SEEE SOCKET Ready 2----->false
TABhs--------------------->2
SECOND CLICK
SEEE SOCKET Ready 1----->false
SEEE SOCKET Ready 2----->false
Server Accept socket connection: /192.168.1.74
SEEE SOCKET Ready 3----->false
TABhs--------------------->4
FOURTH CLICK
SEEE SOCKET Ready 1----->false
SEEE SOCKET Ready 2----->false
SEEE SOCKET Ready 3----->false
Server Accept socket connection: /192.168.1.74
SEEE SOCKET Ready 4----->false
TABhs--------------------->5
I think the problem is at the client's side you read a line and then create a new connection.
I think you must keep reading the socket until it's closed or an error occurs.
For example:
while (true)
{
tabletclient = null;
int loop = 0;
// loop until a connection is established
while (tabletclient == null)
{
try
{
tabletclient = new Socket(SERVER_IP, TAB_SERVER_PORT);
}
catch (Exception e)
{
e.printStackTrace();
// set the value to quit when no connection could be established
if (loop++ > 100)
return;
}
}
try
{
tabletout = new PrintWriter(tabletclient.getOutputStream());
in = new Scanner(tabletclient.getInputStream());
// read the socket until it's closed or an error occurs
try
{
while ((line = in.nextLine()) != null)
{
// my task to be done
}
}
catch (Exception d)
{
System.out.println("Connection from server has lost.........tabletclient.isConnected()----->"
+ tabletclient.isConnected());
}
tabletsocket.close();
}
catch (UnknownHostException e)
{
System.out.println("Entered 2.........");
}
catch (IOException e)
{
System.out.println("Entered 3.........");
e.printStackTrace();
}
}
Also, you must close the server side when the transfer from the server to the client is completed.

communication between groovy and java programs through sockets

I am trying to write a small socket program with client side in groovy and the server side in Java. Below is the code I wrote
client:
def s = new Socket("localhost", 4444);
s << "Server before withStreams\n";
s.withStreams { input, output ->
println"Sending message1"
output << "server message1\n"
}
s.close();
server:
import java.io.*;
import java.net.*;
public class Logger{
ServerSocket providerSocket;
Socket connection = null;
BufferedReader in;
String message="InitialMessage";
Logger(){}
void run()
{
try{
providerSocket = new ServerSocket(4444, 10);
try{
Thread.sleep(1000);
}
catch(InterruptedException ie)
{
System.out.println("Sleep Interrupted");
}
System.out.println("Waiting for connection");
connection = providerSocket.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
do{
if(in.ready())
{
try{
System.out.println(in.read());
message = in.readLine();
System.out.println("client>" + message);
}
catch(IOException e)
{
System.out.println(e);
e.printStackTrace();
break;
}
}
} while(!message.equals("bye"));
}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
//4: Closing connection
try{
in.close();
providerSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}
public static void main(String args[])
{
Logger server = new Logger();
while(true){
server.run();
}
}
}
When I execute both programs, Socket communication is established. But I get a IOException in server code when it reads from the socket (message = in.readLine();)
I guess there is some format problem in writing into socket in client. But not able to figure out the exact problem. Can anybody help?
You generally don't want to close your ServetSocket for each client connection. You want to do this once (or every time you start the server) then on each accept() handle the client connection and close the socket for that connection but keep the ServerSocket open until you want to stop the server.
Here's a rewritten version of your example server that also creates a new Thread for each client request to handle multiple concurrent requests. Note that since the test client doesn't send the terminating string "bye" the connection and socket stays open.
import java.io.*;
import java.net.*;
public class Logger {
private ServerSocket providerSocket;
Logger() {
}
public void start() {
try {
providerSocket = new ServerSocket(4444, 10);
while (true) {
System.out.println("Waiting for connection");
Socket connection = providerSocket.accept();
new Thread(new Job(connection)).start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (providerSocket != null) {
System.out.println("Stopping server");
try {
providerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class Job implements Runnable {
final Socket connection;
private static int id;
private int clientId = ++id;
public Job(Socket connection) {
this.connection = connection;
}
public void run() {
BufferedReader in = null;
try {
System.out.println("Connection " + clientId + " received from " + connection.getInetAddress().getHostName());
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String message = "InitialMessage";
do {
if (in.ready()) {
try {
// not sure why want to read one character then read the line
//int ch = in.read();
//System.out.println(ch);
// -1 if the end of the stream has been reached
//if (ch == -1) break;
message = in.readLine();
// null if the end of the stream has been reached
if (message == null) break;
System.out.println("client>" + message);
} catch (IOException e) {
System.out.println(e);
e.printStackTrace();
break;
}
}
} while (!message.equals("bye"));
} catch (IOException e) {
e.printStackTrace();
} finally {
//4: Closing connection
System.out.println("Close connection " + clientId);
if (in != null)
try {
in.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
try {
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String args[]) {
Logger server = new Logger();
server.start();
}
}

Categories

Resources