JAVA TCP/IP Socket Implementation (3)

Client Actions

Communicate with server

  1. Instantiate a Socket object
  2. Communicate with server
    1. Send data/requests
    2. Receive data/replys
  3. Close the socket
  • Data is exchanged by reading and writing to input and output streams
  • Create a DataOutputStream
  • When creating the DataOutputStream tie it directly to the socket
  • Writing to the DataOutputStream then causes the data to automatically be transmitted to the server
try{
		//  Instantiate an output stream tied directly to the socket
	DataOutputStream oStream = new DataOutputStream(sock.getOutputStream());
		//  write a string and an int to the output stream, 
		//	i.e. transmit them to the server
	oStream.writeUTF("Hello!");
	oStream.writeInt(3);
	oStream.flush(); //tell java to empty the stream right now (= send the information)
}
catch(IOException ioe) {
	System.out.println("Write error: " + ioe.getMessage());
}