Você está na página 1de 20

Sockets and Network Programming

Networks

Client-Server Architecture
Server an application that runs on the host
computer that provides a means of connection and
useful information once a connection is
established.
Client application(s) running on different
computer(s) that seek to establish a connection
and request computation/ information from the
server

a client, a server, and network

Client

Server
Network

Client machine
4

Server machine

What is a Socket?

A door between application process and end


end--to
to--end
end-transport protocol
A socket on one computer can talk to a socket on another
computer via communication channel
Two main types of sockets supported in Java
TCP sockets
k t (implemented
(i l
t db
by th
the S
Socket
k t class)
l
)
UDP sockets (implemented by the DatagramSocket
class)

TCP sockets are generally more commonly used and simpler.

Host and Port


Host
The Ip address of the machine we want to talk to.

Port number
A number identifying a process on the host.
This address is subdivided into 65,536
65 536 ports
Many services run on well-known ports. For
example http tends to run on port 80
example,

Internet addresses
Every host on the Internet is identified by a unique,
four-byte Internet Protocol (IP) address.
This is written in dotted format like 199.1.32.90
where each byte is an unsigned integer between 0
and 255.
There
Th are about
b
four
f
billion
billi unique
i
IP addresses,
dd
but
b
they arent very efficiently allocated

TCP Sockets

TCP is a reliable pointpoint-toto-point communication protocol that


client--server applications on the Internet use to
client
communicate with each other
To communicate over TCP, a client program and a server
program establish a connection to one another
The client and server programs both bind a socket to each
end of the connection and communicate by reading and
writing to those sockets
Th
There
are some commonly
l used
d socket
k t classes
l
iin th
the
java.net package

Java Socket
A socket is a communication end point
Is used by a process to communicate with a remote
system via a transport protocol.
Needs an IP address and a port number

Sockets are popularly used in client/server


computing
Provides two major types of services:
Connection-oriented
Connectionless

Java Socket
Java supports client/server computing using
sockets.
Java uses Socket for clients and ServerSocket for
servers in a connection-oriented environment.
Java uses DatagramSocket/DatagramPacket for
connectionless services.

Server Sockets
Creating and using server sockets
Constructors
ServerSocket(int port)
ServerSocket(int port, int backlog)
Methods
accept()
close()

Description
Waits for a connection request and
returns a Socket
Stops waiting for requests from clients

Client Sockets
Creating client sockets
public Socket()
Socket(String
(
g host,, int pport))

Using client sockets


Methods

Description

getInputStream() Returns an InputStream for receiving data


getOutputStream()
tO t tSt
() Returns
R t
an OutputStream
O t tSt
to
t sendd data
d t
close()
Closes the socket connection

Life cycles of the client/server model


The life cycle of a client
A client socket is created using Socket()
The
Th socket
k connects to a remote host
h
Data exchange between local and remote hosts.
an input
i
stream to readd data
d
an output stream to send data to server.

Connection terminates after transmission of


data is complete.

Life cycles of the client/server model


Life cycle of a server
A server socket is created on a particular port using
ServerSocket().
The socket listens for an incoming connection request
from a client on the port using accept().
Data exchange
g after connection is made.
The server and client interact according to an agreed upon
protocol.
Either or both of getInputStream() and getOutputStream(),
depending on the type of server, is called to exchange data
with the client.

Life cycles of the client/server model


The server, the client, or both closes the
connection upon completion of data exchange.
The server returns to step 2 and waits for the
next connection request.

Another example: Java client (TCP)


import java.io.*;
import java.net.*;
class TCPClient {

Create
input
nput stream
Create
client socket,
connect to server
Create
output stream
attached to socket

public static void main(String argv[]) throws Exception


{
String sentence;
String modifiedSentence;
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("hostname", 6789);
DataOutputStream outToServer =
new DataOutputStream(clientSocket.getOutputStream());

Example: Java client (TCP), cont.


Create
input stream
attached to socket

BufferedReader inFromServer =
new BufferedReader(new
InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();

Send line
to server

outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();

Read line
from server

System.out.println
y
p
(("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
17

Another
example:
Java
server
(TCP)
import java.io.*;
import java.net.*;
class TCPServer {

Create
welcoming socket
att portt 6789
Wait, on welcoming
socket for contact
by client
l
Create input
stream, attached
to socket

public static void main(String argv[]) throws Exception


{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(6789);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
putSt ea
eade (co ect o Soc et get putSt ea ()));

Example: Java server (TCP), cont


Create output
stream, attached
to socket

DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());

Read in line
from socket

clientSentence = inFromClient.readLine();
capitalizedSentence = clientSentence.toUpperCase() + '\n';

Write out line


to socket

outToClient.writeBytes(capitalizedSentence);
}
}

End of while loop,


loop back and wait for
another client connection
19

Sockets
k

Client socket, welcoming socket and connection socket

Você também pode gostar