Prepared by: Eng/ Basma Elshoky
Section 6: sockets III
simple client-server communication
A simple client-server communication setup using sockets.
import [Link].*;
import [Link].*;
import [Link].*;
public class App {
public static void main(String[] args) throws Exception {
//Server
String hostname = "[Link]";
ServerSocket ss = new ServerSocket(1286);
Socket s =[Link]();
OutputStream socketOutStream = [Link]();
DataOutputStream socketDos = new DataOutputStream(socketOutStream);
[Link]("Hello World!");
[Link]();
[Link]();
[Link]();
[Link]();
// Client
Socket s = new Socket("localhost",1286);
InputStream sIn = [Link]();
DataInputStream socketDis = new DataInputStream(sIn);
String testString = new String([Link]());
[Link](testString);
[Link]();
[Link]();
[Link]();
}
}
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 ([Link]) 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