Created
September 1, 2016 03:06
-
-
Save Arinerron/0af6302abf5ba94435e67ae26f31bc3f to your computer and use it in GitHub Desktop.
Read and write directly to a socket from terminal.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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