user2318861
user2318861

Reputation: 131

Java networking IO server setup

I want to play around with the Java networking I/O streams and API. I have a laptop and a PC on my network (I know the IP's to each of these devices) that connects through a Netgear DG834 router.

How would I configure my laptop as the "server" and my PC as the "client" when toying with java networking I/O streams.

Thanks!

Upvotes: 0

Views: 192

Answers (3)

darijan
darijan

Reputation: 9795

You are looking for simple TCP communication using sockets. Take a look at this tutorial, it has it all for you to start: http://systembash.com/content/a-simple-java-tcp-server-and-tcp-client/

Basic idea is to have a server that listens at a certain port:

String clientSentence;          
String capitalizedSentence;          

//server listes at port number
ServerSocket welcomeSocket = new ServerSocket(6789);          

//server is running forever...
while(true) {
    //... and is accepting connections
    Socket connectionSocket = welcomeSocket.accept();

    //receives string messages ...
    BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));             

    //... and sends messages
    DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());             
    clientSentence = inFromClient.readLine();             
    System.out.println("Received: " + clientSentence);             
    capitalizedSentence = clientSentence.toUpperCase() + '\n';              
    outToClient.writeBytes(capitalizedSentence);          
}

And the client should look like this:

String sentence= "this is a message";   
String modifiedSentence;   

//client opens a socket
Socket clientSocket = new Socket("localhost", 6789);   

DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());   
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));   

//writes to the server
outToServer.writeBytes(sentence + '\n');   
modifiedSentence = inFromServer.readLine();   

System.out.println("FROM SERVER: " + modifiedSentence);   

//communication is finished, close the connection
clientSocket.close(); 

Upvotes: 1

Eric Wich
Eric Wich

Reputation: 1544

A large part of Java networking is handled with Sockets. The server is a ServerSocket. The client is a Socket. They connect and speak to each other. That's where you should start, right at the Java API reading about these objects.

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

Upvotes: 1

Bourne
Bourne

Reputation: 1927

You don't need 2 PC's to do this. You can do this in the same PC by configuring java processes to listen to 2 different ports.

Upvotes: 0

Related Questions