Munatas Meddur
Munatas Meddur

Reputation: 41

how can I listen to a certain port using Java?

Sorry I'm asking this, but I'm new to socket programming in general. I'd like to read all the data that comes from a certain port, say 8080. how can I do it? can you give me a simple example, on which I can build a solid understanding?

Thank you!

Upvotes: 0

Views: 53

Answers (2)

Mattias F
Mattias F

Reputation: 632

This listens from a port, gets the socket, creates a reader from the stream and prints every line that comes from the socket:

ServerSocket serverSocket = new ServerSocket(8080);

Socket socket = serverSocket.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

String line = null;
while((line = br.readLine()) != null){
    System.out.println("Line from socket: "+line);
}

From there I'm sure you can go on by yourself

Upvotes: 0

MGorgon
MGorgon

Reputation: 2597

http://docs.oracle.com/javase/7/docs/api/java/net/ServerSocket.html

ServerSocket socket = new ServerSocket(8080);

Upvotes: 2

Related Questions