Definition: A socket is one end-point of a two-way communication link between two programs running on the network.
Types:
Stream socket: class Socket.
Stream socket (To listen): class ServerSocket.
Datagram socket: class DatagramSocket.
Example:
public class EchoTest { public static void main(String[] args) { Socket echoSocket = null; DataOutputStream os = null; DataInputStream is = null; DataInputStream stdIn = new DataInputStream(System.in); try { echoSocket = new Socket("taranis", 7); os = new DataOutputStream(echoSocket.getOutputStream()); is = new DataInputStream(echoSocket.getInputStream()); } catch (UnknownHostException e) { ... } catch (IOException e) { ... } if (echoSocket != null && os != null && is != null) { try { String userInput; while ((userInput = stdIn.readLine()) != null) { os.writeBytes(userInput); os.writeByte('\n'); System.out.println("echo: " + is.readLine()); } os.close(); is.close(); echoSocket.close(); } catch (IOException e) { ... } } } }
Listening and Communicating:
Request channel: Server do the listening.
Communication channel: Created for each connection.
Knock Knock Server:
Server: Knock! Knock! Client: Who's there? Server: Turnip Client: Turnip who? Server: Turnip the heat, it's cold in here! Want another? (y/n)
Classes:
KnockKnockServer: Implements the server
KKState: Implements the application. It keeps track of the current joke, the current state and serves up the various text pieces of the joke depending on the current state.
KnockKnockClient: Implements the client.
Creates a ServerSocket to listen:
try { serverSocket = new ServerSocket(4444); } catch (IOException e) { ... }
Waits until a clients connects:
Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { ... }
Open an input and output stream to the socket:
DataInputStream is = new DataInputStream( new BufferedInputStream(clientSocket.getInputStream())); PrintStream os = new PrintStream( new BufferedOutputStream(clientSocket.getOutputStream(), 1024), false); String inputLine, outputLine; KKState kks = new KKState();
Read from and write to the socket
outputLine = kks.processInput(null); os.println(outputLine); os.flush(); while ((inputLine = is.readLine()) != null) { outputLine = kks.processInput(inputLine); os.println(outputLine); os.flush(); if (outputLine.equals("Bye.")) break; }
Close all the input and output streams:
os.close(); is.close(); clientSocket.close(); serverSocket.close();
Differences from EchoTest:
kkSocket = new Socket("taranis", 4444); . . . while ((fromServer = is.readLine()) != null) { System.out.println("Server: " + fromServer); if (fromServer.equals("Bye.")) break; while ((c = System.in.read()) != '\n') { buf.append((char)c); } System.out.println("Client: " + buf); os.println(buf.toString()); os.flush(); buf.setLength(0); }
Requests treated by one execution thread.
Individual communication treated by:
Another process
Another thread.
Copyright © 1998-2009 Dilvan Moreira