Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

using java; create a new listning port

Status
Not open for further replies.

pollux0

IS-IT--Management
Mar 20, 2002
262
US
I am relativley new to java. However I need to make my application cerate a new port on the server and set it to "listning" so as to wait for another server to connect to it.

thanks in advance
 
First of all look in the Java Documentation for the java.net.ServerSocket class, this has everthing you need in it for creating a socket that will 'listen' for a connection from outside.

But in general

1) Create a ServerSocket Object
Code:
ServerSocket serv = new ServerSocket(portNumber,queueLength)

2) Accept a connection when it is made
Code:
Socket socket = serv.accept()
This call will block indefinately so you may want to put the ServerSocket code in a separate Thread (sometimes it is a good idea, sometimes you want the program to halt until a connection is achieved, it's upto you)

3) You then need get the Input and Output stream associated withthe new socket (same as you do for a standard socket), and them depending on what is being sent you will probably want to wrap the stream in a Buffered handler (for text) or something similar.


Hope it helps. ----------------------------------------
There are no onions, only magic
----------------------------------------
 
To get you started, take a gander at below code - which sets up a ServerSocket, and then invokes another class with each connection to this port - one thread per connection - this enables you to accept multiple connections to your port, and deal with each client request individually.

Post back if there are any bits you need clarification on,

Ben


public class Listen {
public static int port;

public static void main(String argv[]) throws IOException {
port = Integer.parseInt(argv[0]); //PORT TO LISTEN ON - SPECIFIED ON COMMAND LINE
System.out.println("\nListening on port : " +port);

ServerSocket ss = new ServerSocket(port);
while (true)
new ListenConnection(ss.accept()).start();
}
}

class ListenConnection extends Thread {
Socket client;
ListenConnection (Socket client) throws SocketException {
this.client = client;
setPriority( NORM_PRIORITY - 1 );
System.out.println("\nProcessing Thread : " +client);
}

public void run( ) {
processClientRequest(); //DO SOME STUFF WITH CONNECTION
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top