Prepared by: Eng/ Basma Elshoky
Section 6: sockets III
simple client-server communication
A simple client-server communication setup using sockets.
import java.io.*;
import java.net.*;
import java.util.*;
public class App {
public static void main(String[] args) throws Exception {
//Server
String hostname = "www.oreilly.com";
ServerSocket ss = new ServerSocket(1286);
Socket s =ss.accept();
OutputStream socketOutStream = s.getOutputStream();
DataOutputStream socketDos = new DataOutputStream(socketOutStream);
socketDos.writeUTF("Hello World!");
socketDos.close();
socketOutStream.close();
s.close();
ss.close();
// Client
Socket s = new Socket("localhost",1286);
InputStream sIn = s.getInputStream();
DataInputStream socketDis = new DataInputStream(sIn);
String testString = new String(socketDis.readUTF());
System.out.println(testString);
socketDis.close();
sIn.close();
s.close();
}
}
Prepared by: Eng/ Basma Elshoky
Let's break down what each part of the code does:
1. Server Side
- It begins by setting up a server on port 1286 using `ServerSocket`.
- It then waits for a client connection using `accept()` method.
- Once a client connects, it obtains the output stream from the socket, wraps it with
`DataOutputStream`, and sends the string "Hello World!" to the client using `writeUTF()`
method.
- Finally, it closes the streams and sockets.
2. Client Side:
- It creates a socket and connects to the server running on localhost (127.0.0.1) on port 1286
using `Socket` class.
- Then, it gets the input stream from the socket, wraps it with `DataInputStream`, and reads the
string sent by the server using `readUTF()` method.
- It prints the received string ("Hello World!") to the console.
- Finally, it closes the streams and socket.
Here's a step-by-step execution flow:
- Comment a client. Then run the server code, it will wait for a client to connect.
- within running comment the server code, run a client code to connect.
- When you run the client code, it connects to the server.
- The server sends "Hello World!" to the client.
- The client receives "Hello World!" and prints it to the console.
Prepared by: Eng/ Basma Elshoky