Java socke 编程问题,求解答
我想实现多个客户端和一个服务端之间的互相传送报文,现在只做到了客户端向服务端传送,不能双向传送,求解怎么才能做到双向发送报文
程序代码:
package beta; import *; import *; class ServerThreadCode extends Thread { //客户端的socket private Socket clientSocket; //IO句柄 private BufferedReader sin; private PrintWriter sout; //默认的构造函数 public ServerThreadCode() {} public ServerThreadCode(Socket s) throws IOException { clientSocket = s; //初始化sin和sout的句柄 sin = new BufferedReader(new InputStreamReader(clientSocket .getInputStream())); sout = new PrintWriter(new BufferedWriter(new OutputStreamWriter( clientSocket.getOutputStream())), true); //开启线程 start(); } //线程执行的主体函数 public void run() { try { //用循环来监听通讯内容 for(;;) { String str = sin.readLine(); //如果接收到的是byebye,退出本次通讯 if (str.equals("byebye")) { break; } System.out.println("In Server reveived the info: " + str); sout.println(str); } //System.out.println("closing the server socket!"); } catch (IOException e) { e.printStackTrace(); } finally { //System.out.println("close the Server socket and the io."); try { clientSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } public class ThreadServer { //端口号 static final int portNo = 3333; public static void main(String[] args) throws IOException { //服务器端的socket ServerSocket s = new ServerSocket(portNo); System.out.println("The Server is start: " + s); try { for(;;) { //阻塞,直到有客户端连接 Socket socket = s.accept(); //通过构造函数,启动线程 new ServerThreadCode(socket); } } finally { s.close(); } } }