【0】README
1)本文旨在实现 利用网络套接字实现类似qq 的控制台通讯, client 采用telnet and java app, server采用 java app;
2)also, you can check out the source code from https://github.com/pacosonTang/core-java-volume/tree/master/coreJavaAdvanced/chapter3/qq_resembled
3)本代码的问题不足在于 没有实现 server 发送到 多个 client 的 socket 连接,即,server 发送的消息属于群发,而不是 peer to peer 的 发送,如果需要完成这个工作的话,需要 socket 连接池,对于每个 client 都建立相应的 socket,即建立相应的 OutputStream and InputStream;
4)编译本代码,可能会报错(错误:找不到符号),解决方法参见: http://blog.csdn.net/pacosonswjtu/article/details/51804636
【1】server by java app
public class ServerPlainTest {public static void main(String[] args) {try {ServerSocket ss = new ServerSocket(8189);System.out.println("the server has startuped, waiting for connections.");while (true) { // accept multiple clients connection request.Socket s = ss.accept();System.out.println("a client has connected successfully.");new Thread(new ReceiveHandler(s, Role.SERVER)).start();new Thread(new SendHandler(s, Role.SERVER)).start();}} catch (Exception e) {System.out.println(e);}}
}
public class MessageHandler {
}// receive msg.
class ReceiveHandler implements Runnable {private Socket socket;private Role role;public ReceiveHandler(Socket socket, Role role) {this.socket = socket;this.role = role; }public void run() {try {System.out.println(role + " executes ReceiveHandler.run method.");InputStream is = socket.getInputStream();Scanner in = new Scanner(is);// echo client inputboolean done = false;while (!done && in.hasNextLine()) {String line = in.nextLine();System.out.println(line);if (line.trim().equalsIgnoreCase("bye")) {done = true;}}// close relative instance.in.close();} catch (IOException e) {e.printStackTrace();} }
}// send msg.
class SendHandler implements Runnable {private Socket socket;private Role role;public SendHandler(Socket socket, Role role) {this.socket = socket;this.role = role; }public void run() {PrintWriter pw = null;try {System.out.println(role + " executes SendHandler.run method.");Scanner s = new Scanner(System.in);OutputStream os = socket.getOutputStream();pw = new PrintWriter(os, true); // autoFlush=true.if (role.equals(Role.SERVER)) {pw.println("from server: you've connected with the server.");}while (s.hasNext()) {String line = s.nextLine();pw.println("from " + role + ": " + line);}pw.println("connection closed successfully. bye!");} catch (Exception e) {e.printStackTrace();} }
}
【2】client by java app
1)source code is as following
public class ClientPlainTest {public static void main(String[] args) {Socket s = null;try {s = new Socket("localhost", 8189);System.out.println("connection with the server successfully.");new Thread(new ReceiveHandler(s, Role.CLIENT)).start();new Thread(new SendHandler(s, Role.CLIENT)).start();} catch (Exception e) {System.out.println(e);} }
}
2)console info:
【3】client by telnet (connect with server by telnet localhost 8189)