Skip to content

Instantly share code, notes, and snippets.

@nesterchung
Created August 28, 2018 10:03
Show Gist options
  • Save nesterchung/7b9bec5102c5ce3f9c3905c81c49150b to your computer and use it in GitHub Desktop.
Save nesterchung/7b9bec5102c5ce3f9c3905c81c49150b to your computer and use it in GitHub Desktop.
import java.net.*;
import java.io.*;
/**
* Echo socket client
*/
public class Servce {
public static void main(String[] args) {
//open server socket on port 1234
try {
ServerSocket serverSocket = new ServerSocket(1234);
while(!Thread.interrupted()) {
//start a handle thread when accept
new Thread(new Handler(serverSocket.accept())).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
static class Handler implements Runnable {
final Socket socket;
Handler(Socket socket) {
this.socket = socket;
}
public void run() {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(
socket.getInputStream(),
"UTF-8"));
PrintWriter writer = new PrintWriter(
new OutputStreamWriter(
socket.getOutputStream(),
"UTF-8"),
true);
String msg = null;
while((msg = reader.readLine()) != null) {
if (null == msg || msg.isEmpty()) {
writer.println("exit");
break;
}
writer.println(process(msg));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
//ignore
}
}
}
public String process(String in) {
String out = in;
return out;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment