Skip to content

Instantly share code, notes, and snippets.

@Arinerron
Created September 1, 2016 03:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Arinerron/0af6302abf5ba94435e67ae26f31bc3f to your computer and use it in GitHub Desktop.
Save Arinerron/0af6302abf5ba94435e67ae26f31bc3f to your computer and use it in GitHub Desktop.
Read and write directly to a socket from terminal.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("ip:");
final String host = scanner.nextLine();
System.out.print("port:");
final int port = Integer.parseInt(scanner.nextLine());
try {
final Socket socket = new Socket(host, port);
System.out.println("Established connection with " + host + ":" + port + "...");
Thread read = new Thread(new Runnable() {public void run() {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e2) {
try {
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
scanner.close();
System.err.println("[Error] Failed to open input stream.");
System.exit(1);
}
String str = "";
try {
while ((str = br.readLine()) != null) {
System.out.println(str);
}
} catch (IOException e1) {
e1.printStackTrace();
}
try {
br.close();
} catch (IOException e) {
System.err.println("[Error] Socket closed.");
System.exit(1);
}
}});
Thread write = new Thread(new Runnable() {public void run() {
PrintWriter writer = null;
try {
writer = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
try {
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
scanner.close();
System.err.println("[Error] Failed to open output stream.");
System.exit(1);
}
while(true) {
writer.println(scanner.nextLine());
System.out.println("[Sent!]");
}
}});
read.start();
write.start();
} catch(Exception e) {
System.err.println("[Error] Unable to establish connection.");
System.exit(1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment