Transcript socekts
Sockets
• A socket is an object that encapsulates a TCP/IP connection
•There is a socket on both ends of a connection, the client side and the
server side.
•A socket has two streams, one for input and one for output.
•In a client/server application:
the client’ output stream is connected to the server’s input stream
the server’s output stream is connected to the client’s output stream
Typical scenerio:
• Server program creates a socket at a certain port and waits until a client
requests a connection
• Client program creates a socket and attempts to make a connection
• Once the connection is established the client and server communicate
• Client closes connection.
•
A Server
Program
A server application waits
for the
client to connect on a
certain port. We choose 8888
•
To listen for incoming connections, use a server socket
• To construct a server socket, provide the port number
ServerSocket server = new ServerSocket(8888);
•
Use the accept method to wait for client connection:
Socket s = server.accept();
//accept() will wait until a connection is established .. Java will
notify when this happens
•Now can open input/output to socket:
s.getInputStream provides reference to
the socket’s input stream
Client Program
•Syntax to create a socket in a Java program
Socket s = new Socket(hostname, portnumber);
•Code to connect to the HTTP port of server, java.sun.com
final int HTTP_PORT = 80;
Socket s= new Socket("java.sun.com",HTTP_PORT);
•again, now access this sockets input and output stream
InputStream in = s.getInputStream()
OutputSteam out = s.getOutputSTream
• Client socket should close when done:
s.close();
s.
Let’s look at a Server program which ‘echo’s all text
Receives until ‘goodbye’ is received.
… we’ll test it with Telnet (localhost , port=55555)
netSEx5.java
Now, a client to go with it………………