Each client gets the same port number
- From: Petterson Mikael <mikael.petterson@xxxxxxxxxxxxxxx>
- Date: Tue, 10 Jan 2006 09:30:32 +0100
Hi,
I posted a message yesterday when I had problems with "Connection reset" with a server and 2 clients.
When I studied the trace I found out that both clients ( on the same host) get the same port. This is not good or? Should not each connection
generate a new port.
What am I missing?
Cheers,
//Mikael
This is the code in my server:
Server.java ===========
package server;
import java.io.IOException; import java.net.ServerSocket;
import javax.swing.JFrame;
/**
* This class creates a server socket that will
* wait for connections from clients on a specified
* port. For each new connection request from client
* a new ServerThread is created to handle the actual
* communication.
* @author eraonel
*
*/
public class Server extends JFrame {private static final int port = 1234;
private ServerSocket server;
private ServerThread st;
private SrvGui gui;
private String newline = "\n";
public Server(SrvGui srvGui) {
gui = srvGui;
} public static void main(String args[]) {
SrvGui srvGui = new SrvGui();
srvGui.setSize(600, 250);
srvGui.setVisible(true);
Server server = new Server(srvGui);
while (true) {
server.initiate();
}
}
/**
* Method listens for incoming connection attempts.
* When it detects a connection attempt,
* it accepts the connection.
* Socket for communcation is created.
*/
public void initiate() {
gui.display.append("Starting up server on port " + port + newline); try {
// server listens on a specific port
server = new ServerSocket(port);
while (true) {
// Create a separate thread for each client connecting.
st = new ServerThread(server.accept(), gui);
Thread t = new Thread(st);
t.start();
} } catch (IOException ioe) {
gui.display.append("Could not connect " + newline);
System.exit(-1);
}}
/**
* called by the Java virtual machine (JVM)* before the program exits to
* give the program a chance to clean up and release resources
*/
protected void finalize() {
// Objects created in run method are finalized when
// program terminates and thread exits
try {
server.close();
} catch (IOException e) {
System.out.println("Could not close socket");
System.exit(-1);
}
}
/**
* This method is used to "transmitt" a shutdown that is
* done in the thread.
*/
public static void shutdown(){
ServerThread.shutdown();
}}
ServerThread.java =================
package server;
import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.Random;
public class ServerThread implements Runnable {
/** Create a new socket connection */
private static Socket socket = null;
private static ObjectOutputStream out;private static ObjectInputStream in;
private SrvGui gui;
private String newline = "\n";
private boolean keepRunning = true;
/** Random number generator */ private static Random generator = new Random();
public ServerThread(Socket socket, SrvGui gui) {
ServerThread.socket = socket;
this.gui = gui;
}
/** Code to be executed in a separate thread */
public void run() {
setUpStreams();
gui.display.append("Waiting to receive data from client" + newline);
// Client-Server communicate via the input and output streams
while (keepRunning) {
try { String message = recMessage();
if (message != null && !message.equals("bye")) {
String result = calculate(message);
sendMessage(result);
} else if (message.equals("bye")) {
System.out.println("Stopping client thread");
keepRunning = false;
sendMessage("bye");
}
} catch (IOException ioe) {
System.err.println("Server closing connection");
System.exit(-1);
ioe.printStackTrace();
} }
// Always clean up if we receive bye from client.
try {
in.close();
out.close();
socket.close();
System.out.println("....now stopped");
} catch (IOException ioe) {
ioe.printStackTrace();
}}
/**
* Method performs division. A delay is done for
* 5 -10 seconds before the actual calaculation
* is done.
* @param message (n/d)
* @return result, the quotinent.
*/
private String calculate(String message) {
String result = null;
String nom = getNominator(message);
String denom = getDenominator(message);
// read two numbers and calculate quotient
try {
// pause 5-10 sec. before actual calcuation
int milliSeconds = (generator.nextInt(5000) + 5000);
System.out.println("Pausing of seconds:" + milliSeconds);
Thread.sleep(milliSeconds);
Integer n = Integer.parseInt(nom);
Integer d = Integer.parseInt(denom);
System.out.println("Server:Calculating...");
Integer q = quotient(n, d);
result = q.toString();
System.out.println("Result is :" + result);}
// process improperly formatted input
catch (NumberFormatException numberFormatException) {
result = "Enter two integers";
} // process attempts to divide by zero
catch (ArithmeticException arithmeticException) {
result = "Division by zero";
}
//
catch (InterruptedException ie) {
ie.printStackTrace();
}
// process unexpected exception
catch (Exception exception) {
result = exception.getMessage();
}
return result;
} /**
* Actual division is performed here.
*
* @param numerator
* @param denominator
* @return result
* @throws ArithmeticException
*/
private Integer quotient(Integer numerator, Integer denominator)
throws ArithmeticException {
return numerator / denominator;
} /**
* Set up object in/out streams.
*/
private void setUpStreams() {
// gui.display.append("Connection received from "+
// socket.getInetAddress()+"#"+socket.getPort()+newline);
gui.display.append("Set up streams" + newline);
try {
// create an output stream
out = new ObjectOutputStream(socket.getOutputStream());
// empty output buffer
out.flush();
// create input stream
in = new ObjectInputStream(socket.getInputStream());
} catch (IOException ioe) { gui.display.append("In/out streams could not be created" + newline);
}
} /**
* Method writes a String object to ObjectOutputStream.
* Stream is flushed to make sure no old data persists.
* @param msg
* @throws IOException
*/
private void sendMessage(String msg) throws IOException {
out.writeObject(msg);
out.flush();
gui.display.append("Sending result " + msg + " to "
+ socket.getInetAddress() + "#" + socket.getPort() + newline);
} /**
* Method will read String object from ObjectInputStream.
* It also makes sure a connection exists.
* @return
* @throws IOException
*/
private String recMessage() throws IOException {
String message = null;
try {
if (in != null) {
message = (String) in.readObject();
gui.display.append("Received " + message + " from "
+ socket.getInetAddress() + "#" + socket.getPort()
+ newline);
}
} catch (ClassNotFoundException cnfe) {
gui.display.append("Wrong object type" + newline);
cnfe.printStackTrace();
}
return message;
}
/** special for shutdown */
private static void sendShutdown() throws IOException{
if(out != null){
out.writeObject("bye");
out.flush();
System.out.println("Sending result bye to "
+ socket.getInetAddress() + "#" + socket.getPort());
}else{
System.out.println("No connection to client");
}
}
/**
* Method will get nomiator out a String
* , msg, that looks like n/d.
* @param msg
* @return n , nominator.
*/
private String getNominator(String msg) {
int underline = msg.indexOf("/");
return msg.substring(0, underline);
}
/**
* Method will get denomiator out a String
* , msg, that looks like n/d.
* @param msg
* @return d , denominator.
*/
private String getDenominator(String msg) {
int underline = msg.indexOf("/");
return msg.substring(underline + 1);
}
/**
* This method performs a graceful shutdown of server.
*/
public static void shutdown(){
try{
sendShutdown();
}catch(IOException ioe){
System.err.println("Failed to shut down server");
}
System.exit(0);
}} .
- Follow-Ups:
- Re: Each client gets the same port number
- From: Roedy Green
- Re: Each client gets the same port number
- Prev by Date: Re: How to detect circle in a directed graph?
- Next by Date: Re: How much of your RAM can you use with the -Xmx option?
- Previous by thread: must convert PHP script to JSP
- Next by thread: Re: Each client gets the same port number
- Index(es):
Relevant Pages
|
|