Created
August 28, 2018 10:03
-
-
Save nesterchung/7b9bec5102c5ce3f9c3905c81c49150b to your computer and use it in GitHub Desktop.
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.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