Created
November 24, 2022 12:12
-
-
Save SpyrexDE/091e9898759fa05895d240a13ce18b8a to your computer and use it in GitHub Desktop.
Socket Ping Pong
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.BufferedWriter; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.io.OutputStream; | |
import java.io.OutputStreamWriter; | |
import java.net.Socket; | |
import java.net.UnknownHostException; | |
class App { | |
public static final String HOSTNAME = "[HOSTNAME]"; | |
public static int PORT = 1114; | |
public static Socket socket; | |
public static OutputStream os; | |
public static InputStream is; | |
public static void main(String[] args) { | |
connect(); | |
String tInput = ""; | |
while(!tInput.equals("stop")) { | |
System.out.println(receive()); | |
tInput = getTerminalInput(); | |
send(tInput); | |
} | |
} | |
public static void connect() { | |
try { | |
socket = new Socket(HOSTNAME, PORT); | |
os = socket.getOutputStream(); | |
is = socket.getInputStream(); | |
} catch (UnknownHostException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
public static void send(String message) { | |
try { | |
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os)); | |
bw.write(message + "\n"); | |
bw.flush(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
public static String receive() { | |
String data = ""; | |
try { | |
data = new BufferedReader(new InputStreamReader(is)).readLine(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return data; | |
} | |
public static String getTerminalInput() { | |
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); | |
String line; | |
try { | |
line = reader.readLine(); | |
return line; | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment