Socket Programming - Unitec Institute of Technology

Download Report

Transcript Socket Programming - Unitec Institute of Technology

ENTERPRISE JAVA
Socket Programming
Content




Sockets
Streams
Threads
Readings
2
Socket Programming







TCP/IP based network connection
Packet data arrives in order
Delivery of packets is guaranteed
ServerSocket
Socket
InputStream
OutputStream
3
Socket Programming



Application Layer
Programming
Do not need to worry about
how TCP/IP and UDP work
Do not need to worry about
network adaptor, device
driver etc.
Application
(HTTP, ftp, telnet, …)
Transport
(TCP, UDP)
Network
(IP, …)
Link
(device, driver …)
4
Server
import java.io.IOException;
Required Import Statements
import java.net.ServerSocket;
public class Server {
public static void main(String[] args)
Server Port
{
ServerSocket server = null;
try
{
server = new ServerSocket(5000);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
5
Server
Keep serving clients forever
while(true)
{
try
{
Socket socket = server.accept();
Wait for a client to connect
Handle client connection with
Socket object
InputStream is = socket.getInputStream();
StringBuffer mesg = new StringBuffer();
while(true)
{
int data = is.read();
if(data == -1)
{
break;
}
else
{
mesg.append((char)data);
}
Get a reference to Socket’s
InputStream
Read data byte by byte until
the end of stream is reached
Append data to StringBuffer
}
System.out.println(mesg);
}
catch(IOException e)
{
e.printStackTrace();
}
6
Server Sockets

Clients and servers are connected by sockets.


The server side will passively wait for a remote host to
connect



There are two ends to each connection: the client, that is the host
that initiates the connection, and the server, that is the host that
responds to the connection.
A server socket binds to a particular port on the local machine.
Once it has successfully bound to a port, it listens for incoming
connection attempts.
When it detects a connection attempt, it accepts the
connection
7
Server Sockets
ServerSocket
Client
Network
Socket
Server
Socket
1
ServerSocket
Client
Network
3

Server
Socket
2
accept()
This creates a socket between the client and the server over which the client
and the server communicate
8
java.net.ServerSocket

The java.net.ServerSocket class represents a Server
Socket
1. It is constructed on a particular port
2. Then it calls accept() to listen for incoming
connections
3. accept() blocks until a connection is detected
4. Then accept() returns a java.net.Socket object to
perform the actual communication with the client
9
Client
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
Open socket connection to
localhost on port 5000
public class Client {
public static void main(String[] args)
{
try
{
Socket client = new Socket("localhost",5000);
Get a reference to Socket’s
Output Stream
OutputStream os = client.getOutputStream();
os.write("Hello ISCG7425".getBytes());
os.close();
client.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
Use Output Stream’s
write(byte[] data) method
to send string data to
server
11
Reading / Writing Data with a
ServerSocket

ServerSocket objects you create will use their
accept() method to connect to a client.
 There
are no getInputStream() or getOutputStream()
methods for ServerSocket

Instead you use accept() to return a Socket object,
and then call its getInputStream() or
getOutputStream() methods
12
Data Streams



Client and Server must observe the same protocol
Socket Input/Output is data stream oriented
InputStream and OutputStream objects operate on
bytes and byte[] arrays



Using the read(byte[] data) and write(byte[] data) methods
Primitive data types need to be converted to and from
bytes to be transferred across the network
Problems arise if there is a data type mismatch. All the
data types are bytes so can be interpreted as any
other data type.
13
Data Streams

Helper classes that do all the leg work in converting
data to and from bytes
DataInputStream
 DataOutputStream


Have methods to read / write a variety of primitive
data types
Strings
 byte
 int
 short
 float

14
Echo Server
Socket socket = server.accept();
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
while(true)
{
try
{
String mesg = dis.readUTF();
dos.writeUTF("Echo response:"+mesg);
}
catch(EOFException e)
{
break;
}
}
15
Echo Client
Socket client = new Socket("localhost",5000);
DataOutputStream dos = new DataOutputStream(client.getOutputStream());
DataInputStream dis = new DataInputStream(client.getInputStream());
dos.writeUTF("Test Message");
String resp = dis.readUTF();
System.out.println(resp);
client.close();
16
Server Threads

Lots of Socket method calls block waiting for input
accept() – blocks waiting for a client connection
 read() – blocks waiting for input




In a server with only one thread of execution – the
server is blocked and no over tasks can be processed
until the blocking method has finished
Only one client can connect to a single threaded server
at a time
Takes a long time to close and open TCP / IP based
connections – so can’t rely on close() / open to support
multiple clients
17
Server Threads
final Socket socket = server.accept();
Thread serverThread = new Thread() {
public void run() {
try {
InputStream is = socket.getInputStream();
StringBuffer mesg = new StringBuffer();
while(true) {
int data = is.read();
if(data == -1)
break;
else
mesg.append((char)data);
}
System.out.println(this.getName() + "\n"+ mesg);
}catch(IOException e) { /* … Handle exceptions … */ }
}
};
serverThread.start();
18
Threads



Threads should be used whenever a task includes some
sort of long running and blocking input and output
Servers will use one thread per client
Threads allow multiple things to be processed at the
same time
Thread.sleep(100) puts the current thread to sleep for 100
ms
 Make sure your server loop includes a Thread.sleep()
method to give up priority to other threads
 All the code executed in a Thread is included in the run()
method – a thread is stopped once the run() method finishes

19
Exercises
1.
2.
3.


Setup code to allow a user to input a user nickname. Send
the user handle to the server using a REGISTER_CLIENT
message, and to other clients using a REGISTER_BROADCAST
message. Setup code to implement both messages.
Setup a new JList component to allow the chat client to
display in list format the names / handles of the other users
logged into the Server.
Allow a user to select a client from the list of logged in users,
and allow the system to send that user a private message.
Team work 3-4 students; different teams to last time
Final due date 30/03/2015 23:55
20
Readings



http://mindprod.com/jgloss/thread.html
http://docs.oracle.com/javase/tutorial/networking/
sockets/
http://docs.oracle.com/javase/tutorial/essential/io
/index.html
21