JAVA TCP/IP Socket Implementation (3)
Client Actions
|
Communicate with server
|
- Instantiate a Socket object
- Communicate with server
- Send data/requests
- Receive data/replys
- 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());
}