Skip to content

Instantly share code, notes, and snippets.

@MrSnor
Last active October 2, 2023 07:38
Show Gist options
  • Select an option

  • Save MrSnor/d67fec2ef5ab84673e2890868300deac to your computer and use it in GitHub Desktop.

Select an option

Save MrSnor/d67fec2ef5ab84673e2890868300deac to your computer and use it in GitHub Desktop.
Simple Java Server and Client (to send and receive a message)
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String args[]) {
try {
// Now we will create a socket object and connect it to the server
// Here localhost means that the server is running on the same machine as the
// client
// If the server is running on a different machine then we will have to enter
// the IP address of that machine instead of localhost
// 3000 is the port number on which the server is running
Socket socket = new Socket("localhost", 3000);
System.out.println("Connected to server at " + socket);
// Now we will create an object of DataOutputStream to send the message to the
// server
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
Scanner sc = new Scanner(System.in);
// Now we will ask the user to enter the message that he wants to send to the
// server
System.out.println("Enter the message that you want to send to the server:");
String message = sc.nextLine();
// Now we will send the message to the server
out.writeUTF("message = " + message);
// Now we will close the connection
out.flush();
// flush method forces any buffered output bytes to be written out
out.close();
socket.close();
sc.close();
}
// If any exception occurs we will print it on the console
catch (Exception e) {
System.out.println(e);
}
}
}
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String args[]) {
try {
// Instantiate a ServerSocket object and bind it
// to port 3000
// This will simply run the server on port 3000
ServerSocket server = new ServerSocket(3000);
System.out.println("Server started. Listening on port " + 3000);
// Now we will wait for the client to connect to our server
// The accept() method will block the execution until a client connects to the
// server
Socket socket = server.accept();
System.out.println("Client connected: " + socket);
// Now we will create and object of DataInputStream to read the message sent by
// the client
DataInputStream in = new DataInputStream(socket.getInputStream());
String message = in.readUTF();
System.out.println(message);
// Now we will close the connection
server.close();
} catch (Exception e) {
// If any exception occurs we will print it on the console
System.out.println(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment