- Forward


Customizing TCP Sockets
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • TCP Sockets:
    • Are very versatile
    • But there are times when applications programmers need to develop specializations
  • Examples:
    • To handle different types of messages
    • To handle different types of handshaking
Possible Approaches
Back SMYC Forward
  • Extension:
    • Override some methods in the existing class and inherit others
  • Decorator Pattern:
    • The decorator implements the same interface as the decorated
    • The decorator delegates to methods in the decorated class
  • Simple Delegation:
    • The decorator delegates some method calls but doesn't implement the same interface as the decorated
An Example
Back SMYC Forward
  • The Type of Application:
    • A connection-oriented "chat" application
  • Requirements:
    • Logon and logoff messages
    • Chat messages
    • Error messages
  • One Solution:
    • A socket that can handle different kinds of payloads
    • Use "frames" that contain a header and (possibly empty) payload
An Example (cont.)
Back SMYC Forward

The Header (6 bytes)

Offset Size Type
0 1 '*' (i.e., the ASCII literal *)
1 1 Frame Type
2 2 Sequence Number
4 2 Data Length

An Example (cont.)
Back SMYC Forward

Valid Frame Types

Code Frame Type
1 SIGNON
2 DATA
3 ERROR (For future use)
4 SIGNOFF (For future use)
5 KEEP_ALIVE (For future use)

An Example (cont.)
Back SMYC Forward
  • Some Design Considerations:
    • The Socket class uses streams, so we need to take that into consideration
    • We should be able to use a "custom socket" the same way as a Socket
    • We're not really adding functionality to the Socket, we're adding functionality to the stream
  • Conclusion:
    • Decorate the streams
    • Extend the socket
An Example (cont.)
Back SMYC Forward

An Input Stream for a Simple Framing Protocol

javaexamples/sfp/SFPInputStream.java
 
An Example (cont.)
Back SMYC Forward

An Output Stream for a Simple Framing Protocol

javaexamples/sfp/SFPOutputStream.java
 
An Example (cont.)
Back SMYC Forward

A Socket for a Simple Framing Protocol

javaexamples/sfp/SFPSocket.java
 
An Example (cont.)
Back SMYC Forward

A Server Socket for a Simple Framing Protocol

javaexamples/sfp/SFPServerSocket.java
 
A More Flexible Design
Back SMYC Forward

Use a Factory

custom_sockets_java
There's Always More to Learn
Back -