tcp sockets ( in java)

28
TCP Sockets (In Java) Don McGregor Research Associate MOVES Institute [email protected]

Upload: hilary-walls

Post on 31-Dec-2015

50 views

Category:

Documents


3 download

DESCRIPTION

TCP Sockets ( In Java). Don McGregor Research Associate MOVES Institute. [email protected]. TCP. As mentioned before, TCP sits on top of other layers (IP, hardware) and implements • Reliability • In-order delivery • No duplicates • Rate-limiting - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: TCP Sockets ( In Java)

TCP Sockets(In Java)

Don McGregor

Research Associate

MOVES Institute

[email protected]

Page 2: TCP Sockets ( In Java)

TCP

As mentioned before, TCP sits on top of other layers (IP, hardware) and implements

• Reliability• In-order delivery• No duplicates• Rate-limitingIt allows you to write to another host on the network

as if it were a file streamTCP only passes bytes; it is completely agnostic about

what they mean. Making sense of the bytes is up to you, the programmer (or the protocol receiving the bytes)

Page 3: TCP Sockets ( In Java)

Review

To connect to a host, we need to specify:• What host we will be talking to, either

directly via IP number, or indirectly via DNS name

• What port on the host we will be talking to; a number in the range 0-64K

Page 4: TCP Sockets ( In Java)

Socket

A “socket” describes a connection between two hosts. To set up a stream between two hosts you need a “socket pair” that describes the connection between the client and the server

Server

172.20.40.12

Client

172.20.40.88

Port TCP 4567 Port TCP 4485

Page 5: TCP Sockets ( In Java)

Socket

The socket pair can be described as ((172.20.40.12, 4567), (172.20.40.88, 4485))

The client IP, a client port, the server IP, and the well-known port we connect to on the server

If you’re picky, you also need to specify whether this is TCP or UDP. This is often omitted, though, because it’s usually clear from the context which is being used

This “socket pair” uniquely describes a connection on the network

Page 6: TCP Sockets ( In Java)

Server Socket

The standard technique is: client initiates connection to server

Before we can establish a connection, we have to have something waiting for the connection on the server side

This is a “server socket”, a piece of software that waits for clients to connect.

Page 7: TCP Sockets ( In Java)

Server Socket

Waiting for a connection at 172.20.40.88, 4485

Server

172.20.40.12

Client

172.20.40.88

Port TCP 4567 Port TCP 4485

Page 8: TCP Sockets ( In Java)

Multiple Connections

What if two people want to connect to a web server at the same time?

Notice that the socket connection has a unique ID based on the socket pair. If two hosts connect, or even if two programs from the same host connect

You can see this with “netstat -an”

Page 9: TCP Sockets ( In Java)

Netstat

hodad-5:MV3500 mcgredo$ netstat -anActive Internet connections (including servers)Proto Recv-Q Send-Q Local Address Foreign Address (state)tcp4 0 411 192.168.1.6.57583 74.125.53.95.80 ESTABLISHEDtcp4 0 406 192.168.1.6.57582 74.125.53.95.80 ESTABLISHEDtcp4 0 0 192.168.1.6.57581 64.236.68.229.80 ESTABLISHED

Page 10: TCP Sockets ( In Java)

Two Connections from Same Host

Server

172.20.40.12

Client

172.20.40.88

Port TCP 4567 Port TCP 4485

Port TCP 4568 Port TCP 4485

What are the socket pairs here?

Page 11: TCP Sockets ( In Java)

Connection Process (Java)

The server starts a server socket on a port; this will listen on, for example 172.20.81.12 on port 1234

The client initiates a connection from its IP to the server. The client picks an unused port on the client machine, and this port is used in the socket pair. The client port is sometimes called an “ephemeral port”

At this point we have a socket pair. The client code returns a socket object, and the server code returns a similar socket object

Note that a Socket object is not a ServerSocket object!

Page 12: TCP Sockets ( In Java)

Socket

Socket

InputStream

InputStream

OutputStream

OutputStream

The inputStream on one side of theSocket is connected to the outputStreamOn the other side, and vice versa

Page 13: TCP Sockets ( In Java)

Input & Output Streams

Input & Output streams are standard Java objects that know how to read & write bytes only. They don’t know about higher level concepts like Unicode characters, integers, floating point numbers, etc

But: are you convinced that with enough work you could write a class that figured out what four bytes represented as a floating point number?

Luckily for you, there are classes in the standard Java library that do this for you

Page 14: TCP Sockets ( In Java)

Input & Output Streams: Text

PrintStream OutputStream

Unicode representation of data

InputStreamInputStream

ReaderBufferedReader

Page 15: TCP Sockets ( In Java)

Other Streams

There are also Java library streams for reading & writing binary values, and streams for reading and writing Java objects (!)

Remember, bytes are bytes; sockets are agnostic about what they mean. We have to come to some sort of a priori agreement on what we’ll be sending so we’ll know what to expect on the receiving side

The string value “17.4” is not the same as a binary floating point number representing 17.4

Page 16: TCP Sockets ( In Java)

16

Framing

• Notice that the TCP socket is sending a stream of bytes. How do the programs on either side know where a particular message starts and ends?

• Remember, the TCP socket treats this as one long array of bytes

Command 1Command 2Command 3

OutputStream(Sender)

InputStream(Receiver)

Page 17: TCP Sockets ( In Java)

17

Framing

• The standard way to do this when the contents of the TCP stream is text is to use newline characters. When the reader comes across a newline it realizes that the command has ended and it can process it

• Be careful to define an agreed-upon newline character—not all operating systems use the same character(s)

Command1\nCommand2\nCommand3\n

Page 18: TCP Sockets ( In Java)

Example Code

See TcpServer.java, TcpClient.javaThis simply establishes a connection and

sends a simple message and response

Page 19: TCP Sockets ( In Java)

Message Format?

So what type message should you send?Since you get to make it up, it’s good for you if you

pick something simple and robustFor TCP sockets sending state updates or commands,

this is usually ASCII textWhy? • Binary is different from host to host• You can easily debug ASCII• it is usually fast enough for what TCP doesYou can use binary formats, but your default first

attempt should be ASCIIBinary content on TCP sockets are good for bulk

transfers of data

Page 20: TCP Sockets ( In Java)

20

Telnet

• Telnet is a very old utility that has a handy side effect: it can be used to establish a client TCP connection to a port server, and send commands– On windows, install with

• pkgmgr /iu:”TelnetClient”

– Should already be present on OS X– Install with yum install telnet on RHEL– Install with apt-get install telnet on Ubuntu

Page 21: TCP Sockets ( In Java)

Examples of TCP Message Formats

You can establish your own interactive TCP connection to a server with “telnet <hostname> <port>” (usually typing blind on windows machines)

HTTP (web servers):• mcgredo$ telnet nps.edu 80

Trying 205.155.65.20…

Connected to nps.edu.

Escape character is '^]’.

GET /index.html HTTP/1.0

Page 22: TCP Sockets ( In Java)

HTTP

• telnet www.nps.edu 80 GET /index.html HTTP/1.0 (two returns)

HTTP/1.1 200 OKCache-Control: no-cacheContent-Type: text/htmlLast-Modified: Tue, 16 Sep 2014 21:01:17 GMTAccept-Ranges: bytesETag: "a34be15bf1d1cf1:0"Server: Microsoft-IIS/7.5X-Powered-By: ASP.NETAccess-Control-Allow-Origin: *Date: Tue, 16 Sep 2014 22:58:25 GMTConnection: closeContent-Length: 11200

Page 23: TCP Sockets ( In Java)

23

SFTP

• Secure File Transfer Protocol (SFTP) allows you to transfer files and list directory contents on a remote host

• sftp [email protected] [email protected] to savage.nps.edu.sftp> lsxj3d_code xj3d_code.dump xj3d_website xj3d_website.dump cd ppp-2.4.5ls Changes-2.3 FAQ

Page 24: TCP Sockets ( In Java)

Stateless vs. Stateful Protocols

Note a subtle difference between the HTTP and SFTP protocols

HTTP is stateless--you send one text command, the server processes that, and then the socket connection can be torn down and the server completely forgets that it ever talked to you before

A stateful protocol depends on prior commands sent from the client. The ls and cd commands depend on the prior commands sent.

Stateless protocols are good. They scale well, and are simple.

Stateful protocols are inherently more complex, because you need to keep track of program state

Page 25: TCP Sockets ( In Java)

Sequential vs Parallel

What happens to our simple ping-pong example if the server takes a long time to process a command?

How can we fix this?Use a thread per client connection--then

we can go back and do another accept() wile the first command is still processing

This is a parallel server

Page 26: TCP Sockets ( In Java)

TCP Protocols

• You want to use text for the protocol commands if you possibly can

• Keep it simple. Simple can be debugged and may actually work. Complex will not. If you possibly can, start off with a sequential, stateless server

Page 27: TCP Sockets ( In Java)

Matrix

Stateless

Stateful

Sequential Parallel

X

Try for a stateless, sequential protocol if you can, on thegrounds that it’s simple. Going to a parallel implementationis not bad, but a stateful protocol can be much more complex

Page 28: TCP Sockets ( In Java)

Assignment

Write a client and server that accepts a simple position command for an entity. Include an entity identifier and position (x,y,z)

Write a simple HTTP client program that sends a request for a URL to a server and gets a response back