Sat Oct 30 2021

Client Server Socket

File Name: client-server-socket-connect.java

/* Client Server message passing using socket */

/* Server side socket */
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class serverSocaket {
	public static void main(String args[]) throws Exception {
		int port = 8888;
		String str;
		ServerSocket srvSocket = new ServerSocket(port);
		System.out.println("Waiting for a connection on " + port);
		Socket clntSocket = srvSocket.accept();
		PrintWriter pw = new PrintWriter(clntSocket.getOutputStream(), true);
		BufferedReader br = new BufferedReader(new InputStreamReader(clntSocket.getInputStream()));

		/* Receive message from client */
		while ((str = br.readLine()) != null) {
			System.out.println("Client message: " + str);

			/* Send message to client */
			if (str.equals("Bye")) {
				pw.println("Bye");
				break;
			}
			else
				pw.println(str);
		}
		pw.close();
		br.close();
		clntSocket.close();
	}
}


/* Client side socket */
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

public class clientSocket {
	public static void main(String args[]) throws Exception {
		String str;
		Socket sckt = new Socket(InetAddress.getLocalHost(), 8888);
		BufferedReader br = new BufferedReader(new InputStreamReader(sckt.getInputStream()));
		PrintWriter pw = new PrintWriter(sckt.getOutputStream(), true);

		/* Send message to server */
		pw.println("Connected");
		pw.println("Hello");

		/* Receive message from server */
		while ((str = br.readLine()) != null) {
			System.out.println("Server message: "+str);
			pw.println("Bye");
			if (str.equals("Bye"))
				break;
		}
		br.close();
		pw.close();
		sckt.close();
	}
}





/* Output */
Compile client and server program, after that start server then client.

/* Server side */
Waiting for a connection on 8888
Client message: Connected
Client message: Hello
Client message: Bye


/* Client side */
Waiting for a connection on 8888
Server message: Connected
Server message: Hello
Server message: Bye
Reference:

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.