• 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
  • Ron McLeod
  • Junilu Lacar
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Piet Souris
  • Carey Brown
  • Stephan van Hulst
Bartenders:
  • Frits Walraven
  • fred rosenberger
  • salvin francis

communicate question for socket server and client

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I created a simple socket server and a socket client
The server receive request from server and send same request back to the client.
Please see example code as below:

// socket server
package socket;

import java.net.*;
import java.io.*;

public class SimpleServer {
public SimpleServer(int listen_port) {
this.listen_port = listen_port;
}
public static void main(String[] args) {
SimpleServer server = new SimpleServer(4444);
server.acceptConnections();
}
public void acceptConnections() {
try {
ServerSocket server = new ServerSocket(listen_port);
Socket incomingConnection = null;
while (true) {
incomingConnection = server.accept();
handleConnection(incomingConnection);
}
} catch (BindException e) {
System.out.println("Unable to bind to port " + listen_port);
} catch (IOException e) {
System.out.println("Unable to instantiate a ServerSocket on port: " + listen_port);
}
}
public void handleConnection(Socket incomingConnection) {
try {
InputStream inputFromSocket = incomingConnection.getInputStream();
BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputFromSocket));
PrintWriter streamWriter = new PrintWriter(incomingConnection.getOutputStream());
StringBuffer sb = new StringBuffer();
String line = null;
int i = 0;
while((line=streamReader.readLine())!=null){
streamWriter.println(line);
break;
}
streamWriter.close();
streamReader.close();
incomingConnection.close();
} catch (Exception e) {
}
}
protected int listen_port;
}


//socket client

package socket;


import java.io.*;
import java.net.*;
import java.util.Iterator;
import java.util.List;
import java.math.*;




public class Simple {

public Simple(String host_ip, int host_port) {
this.host_ip = host_ip;
this.host_port = host_port;
}

public static void main(String[] args) {
Simple simple = new Simple("192.168.254.134", 4444);
simple.setUpConnection();
try {

String result = simple.getResponse("This is first request");
String result2 = simple.getResponse("This is second request");
simple.tearDownConnection();
}
catch (Exception e) {
System.out.println("error");
e.printStackTrace();
}
}

public void setUpConnection() {
try {
// Create new socket object
Socket client = new Socket(host_ip, host_port);

socketReader = new BufferedReader(new InputStreamReader(client.
getInputStream()));
socketWriter = new PrintWriter(client.getOutputStream());
} catch (UnknownHostException e) {
System.out.println(
"Error setting up socket connection: unknown host at " +
host_ip + ":" + host_port);
}
catch (IOException e) {
System.out.println("Error setting up socket connection: " + e);
}
}
public String getResponse(String request) {
StringBuffer fileLines = new StringBuffer();
try {
socketWriter.println(request);
socketWriter.flush();

String line = null;
int i = 0;
int chars = 0;
int sizeOfBuffer = 100;
char[] cbuf = new char[sizeOfBuffer];
while ( (chars = socketReader.read(cbuf)) >= 0) {
fileLines.append(cbuf, 0, chars);
}

} catch (Exception e) {
e.printStackTrace();
}
return fileLines.toString();
}


public void tearDownConnection() {
try {
socketWriter.close();
socketReader.close();
} catch (IOException e) {
System.out.println("Error tearing down socket connection: " + e);
}
}

protected BufferedReader socketReader;
protected PrintWriter socketWriter;
protected String host_ip;
protected int host_port;
}


I send two request at the same time.
Please see code in main method of Simple class

String result = simple.getResponse("first");
String result2 = simple.getResponse("second");

What I think is the socket server will send the same request back to the client.
So value of result and result2 should be 'first' and 'second'
But it always return empty String for result2.
What's the problem?


Thanks for your help





 
Ranch Hand
Posts: 283
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Hongqing Lu,

Your server's socket shuts down as soon as you have sent the first string.

The client is still trying to talk to that socket.

One way to fix it is to move the "setUpConnection" call into the start of "getResponse" method so that a new socket is set up for each string. You would also need to make the client socket a class variable so it becomes accessable to "tearDownConnection".

Alternately, you could make the server socket continue listening after receiving the first string, but then you would need some key word to make the server stop listening to that socket and get the next user to connect.

Hope that helps!

Ed
 
Hongqing Lu
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for your reply Ed.
It's easy to fix it use first method you mentioned.
The trouble is the client should remain the same and don't need to
create a new one.

Maybe it can be implemented with second method. But I really have no idea about how to resolve it.

Could you give me more detail?

Any material is welcome

Thanks a lot
 
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello I modified the program:


Do not ignore an exception, especially when testing!
Notice that println also writes a LF and CR to the socket.
This EOL is going to be recognized by BufferedReader.readLine at "the server side". But the string returned by this method does not contains the EOL.

 
Don't touch me. And dont' touch this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic