Java Socket Programming - TCP
Compared to UDP there are some differences:
The client must contact the server:
- The server process must first be running.
- The server must have created a socket that welcomes the client’s contact.
Clients contact the server by:
- Creating TCP socket, specifying IP address, port number of server process.
- When the cloent creates a socket the slcinet TCP establishes connection to server TCP.
When contacted by the client, the server TCP creates a new socket for the server process to communcate with that particular client:
- This allows the server to talk iwht multiple clients.
- Source port number are used to distinguish clients.
TCP provides a reliable, in-order byte-stream transfer (pipe).
Example Program
Like the UDP example the client sends a string the the server over TCP. The server then converts the string to upper-case and then sends it back.
Java TCP Client
import java.io.*;
import java.net.*;
class TCPClient {
public static void main(String argv[]) throws Exception {
String sentence;
String modifiedSentence;
// create input stream
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
// create client socket and connect to server
Socket clientSocket = new Socket("hostname", 6789);
// create output stream attached to socket
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
// create input stream attached to socket
Buffered Reader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence inFromUser.readLine();
// send line to server
outToServer.writeBytes(sentence +'\n');
// read line from server
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
Java TCP Server
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception{
String clientSentence;
String capitalisedSentence;
// create welcoming socket at port 6789
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true) {
// wait on welcoming socket for contact by client
Socket connectionSocket = welcomeSocket.accept();
// create input stream attached to socket
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
// create output stream attached to socket
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
// read in line from socket
clientSentence = inFromClient.readLine();
capitalisedSentence = clientSentence.toUpperCase() +'\n';
// write out line to socket
outToClient.writeBytes(capitalisedSentence);
}
}
}