In Java or .NET, how would you create a server that listens to a specific port?
In Java or .NET, how would you create a server that listens to a specific port?
(Just a du开发者_运维知识库mmy server, I just want to get the high level idea.)
Suggest Sun's Learning Trail tutorial on writing a client and server for Java.
The key code you need (copied from the above link) is:
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
System.exit(-1);
}
Not sure what you mean by "server", but yes, in .NET you can have a TcpListener
listening on a specified port. I'm sure Java has something similar as well.
For Java, look up java.net.ServerSocket.
There is a tutorial here: http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html.
Veery high level:
import java.io.*;
import java.net.*;
import java.util.Date;
public class Xyz {
public static void main( String [] args ) throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
while( true ) {
final Socket client = serverSocket.accept();
Thread thread = new Thread( new Runnable() {
public void run() {
handle( client ); // custom method
}
});
thread.start();
}
}
public static void handle( Socket client ){
try {
PrintStream out = new PrintStream( client.getOutputStream() );
out.println( new Date().toString() );
out.close();
client.close();
} catch ( IOException e ){
}
}
}
That would open port 8080 and will accept connections. Each connection ( Socket ) will be attended in different threads by the handle
method of this class ( which here just print the current date )
This is veeeeery high level. You'll need to add handling exception, concurrency, and of course you'll have to implement the handle
method it self.
精彩评论