可以一直輸入,而不是一問一答:
開兩個執行緒,一個負責收,一個負責發。
1.先執行:
package com.zr.javase0825; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class User1 implements Runnable { //String pdd="read"; Socket sock; //Socket sockC; public static void main(String[] args) { User1 u1=new User1(); ServerSocket ssock; try { ssock = new ServerSocket(1234); u1.sock=ssock.accept(); // u1.sockC=new Socket("127.0.0.1",5678); Thread t1=new Thread(u1,"read"); Thread t2=new Thread(u1,"write"); t1.start(); t2.start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void read(Socket sock){ try { BufferedReader buff=new BufferedReader(new InputStreamReader(sock.getInputStream())); System.out.println("user2:"+buff.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void write(Socket sockC){ try { BufferedWriter buff=new BufferedWriter(new OutputStreamWriter(sockC.getOutputStream())); BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); String str= bf.readLine(); buff.write(str+"\n"); buff.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void run() { if(Thread.currentThread().getName().equals("read")) while(true) read(sock); else while(true) write(sock); } }
後執行:
package com.zr.javase0825; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.util.Scanner; public class User2 implements Runnable { //String pdd="read"; Socket sock; //Socket sockC; public static void main(String[] args) { User2 u1=new User2(); //ServerSocket ssock; try { //ssock = new ServerSocket(5678); //u1.sock=ssock.accept(); u1.sock=new Socket("127.0.0.1",1234); Thread t1=new Thread(u1,"read"); Thread t2=new Thread(u1,"write"); t1.start(); t2.start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void read(Socket sock){ try { BufferedReader buff=new BufferedReader(new InputStreamReader(sock.getInputStream())); System.out.println("user2:"+buff.readLine()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void write(Socket sockC){ try { BufferedWriter buff=new BufferedWriter(new OutputStreamWriter(sockC.getOutputStream())); BufferedReader bf=new BufferedReader(new InputStreamReader(System.in)); String str= bf.readLine(); buff.write(str+"\n"); buff.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void run() { Scanner in=new Scanner(System.in); if(Thread.currentThread().getName().equals("read")) while(true) read(sock); else while(true) write(sock); } }