Java Sockets Brad Vander Zanden Agenda What are
Java Sockets Brad Vander Zanden
Agenda • • What are sockets Client/Server interaction Single client/server example Synchronized data objects Multi-threaded servers Multi-threaded clients Detecting client/server shutdown
Socket • One end-point of a two-way communication link between two programs running on the network – Typically one process is called the server – Typically one process is called the client server p o rt lis te n Connection Request p o r t client
Server/Client Interaction (from Jonathan Engelsma’s Java Sockets Tutorial-https: //www. youtube. com/watch? v=a. EDV 0 Wlw. XTs) Processing New Socket. Server accept read write close Server Synchronization Point New Socket Communication write read stdin stdout Client close
Single Client/Server Example • echo client – try with resources only works for Java 1. 7 or later – hydra machines have Java 1. 6 (4/2014)
Synchronized Data Objects Data Object New Socket. Server accept read Processing write close Server Synchronization Point New Socket Communication write read stdin stdout Client close
Synchronized Data Objects Not Who’s There • Knock Server Example WAITING Serve “Bye” No ANOTHER serve “Knock” k” c o n Yes ck. K o n “K e erv s Input matches Clue + “who” serve answer + “Want another? ” serve “Knock” SENTKNOCK Serve Who’s Clue There? SENTCLUE Serve “Try again. Knock” Input does not match Clue + “who”
Multi-Threaded Servers • Multi-Threaded Knock Example
Multi-Threaded Client • Chat Example New Socket write read Client client thread stdin stdout close
Multi-Threaded Client (Pseudo Code) Main Thread Write. Console. Thread While (more Socket Read Obj) New Socket Process line Get Socket. Read and Write to console Socket. Write objects Create Write. Console. Thread w/ Socket. Read obj While (more Stdin) Process/Write to Socket. Write Obj
Detecting client/server shutdown • Occurs when socket read object returns null – Socket. close() on other end does not signal other process of termination • Server thread: Exit while loop, wrap up processing, and terminate
Multi-Threaded Client (Detecting Shutdown) Main Thread New Socket interrupted = false Get Socket. Read and Socket. Write objects Create Write. Console. Thread w/ Socket. Read obj While (more Stdin) if (interrupted) break Process/Write to Socket. Write Obj Write. Console. Thread While (more Socket Read Obj) Process line Write to console Notify Main thread of server shutdown by setting interrupted to true
- Slides: 12