Skip to content

Instantly share code, notes, and snippets.

@maxcai314
Created January 14, 2026 18:34
Show Gist options
  • Select an option

  • Save maxcai314/9f0fcb15122254a7f425c4d39e5d4d02 to your computer and use it in GitHub Desktop.

Select an option

Save maxcai314/9f0fcb15122254a7f425c4d39e5d4d02 to your computer and use it in GitHub Desktop.
TCP Communication Demo
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException {
String ip = "10.0.0.20"; // obtain using server's ipconfig (windows), ifconfig (mac, linux)
int port = 1234; // obtain the server's port
var socket = new Socket(ip, port);
var socketIn = socket.getInputStream();
var systemScanner = new Scanner(System.in);
var socketScanner = new Scanner(socketIn);
var socketOut = new PrintStream(socket.getOutputStream(), true);
System.out.println("Please enter your username:");
String username = systemScanner.nextLine();
String prefix = "<" + username + ">: ";
System.out.println("\nWelcome to the chatroom! Type a message and press enter to send it.");
while (true) {
if (System.in.available() > 0) {
String message = systemScanner.nextLine();
System.out.println(prefix + message); // print to own console
socketOut.println(prefix + message); // print to server socket
}
if (socketIn.available() > 0){
String message = socketScanner.nextLine();
System.out.println(message); // print to own console
}
}
}
}
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.util.Scanner;
public class Server {
public static void main(String[] args) throws IOException {
// my device's ip: 10.0.0.20
// find using ifconfig on mac, ipconfig on windows
int port = 1234;
var serverSocket = new ServerSocket(port);
var socket = serverSocket.accept();
var socketIn = socket.getInputStream();
var systemScanner = new Scanner(System.in);
var socketScanner = new Scanner(socketIn);
var socketOut = new PrintStream(socket.getOutputStream(), true);
System.out.println("Please enter your username:");
String username = systemScanner.nextLine();
String prefix = "<" + username + ">: ";
System.out.println("\nWelcome to the chatroom! Type a message and press enter to send it.");
while (true) {
if (System.in.available() > 0) {
String message = systemScanner.nextLine();
System.out.println(prefix + message); // print to own console
socketOut.println(prefix + message); // print to server socket
}
if (socketIn.available() > 0){
String message = socketScanner.nextLine();
System.out.println(message); // print to own console
}
}
}
}
@maxcai314
Copy link
Author

To find your local IP address, run ipconfig in the windows terminal or ifconfig on mac/linux, and search for the IP address associated with the en0 network interface.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment