Java简单客户端/服务器读/写

时间:2013-07-05 20:01:38

标签: java client-server bufferedreader printwriter

我正在尝试在客户端和服务器之间进行简单聊天或双向通信

我面临的问题是,如果我继续在任何一方输入新文本然后没有显示...只有第一个输入的文本显示。

从服务器端输入一次文本,从客户端输入一次后,服务器端和客户端都退出。

Server
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class Server {
    ServerSocket server;
    Socket s;
    InputStream input;
    OutputStream out;
    Scanner in=new Scanner(System.in);
    BufferedReader br;
    PrintWriter pw;
    String str1;
    String str2;
    public void create() throws Exception{
       server=new ServerSocket(40000);
       System.out.println("Begin :) Server");
       s=server.accept();
       input=s.getInputStream();
       out=s.getOutputStream();
       br=new BufferedReader(new InputStreamReader(input));
       pw=new PrintWriter(out);
       t1.start();
       t2.start();
    }
    Thread t1=new Thread(new Runnable(){
        @Override
        public void run (){
         str1=in.nextLine();
         pw.println(str1);
         pw.flush();
        }
    });
    Thread t2=new Thread(new Runnable(){
        @Override
        public void run(){
           try{
            str2=br.readLine();
           }catch(Exception e){}
           System.out.println(str2);
        }
    });
    public static void main(String[] args) throws Exception{
       Server s=new Server();
       s.create();       
    }
}


Client
import java.util.Scanner;
import java.net.*;
import java.io.*;
public class Client {
    Socket s;
    InputStream input;
    OutputStream out;
    BufferedReader br;
    PrintWriter pw;
    Scanner in;
    String str1;
    String str2;
    public void create() throws Exception{
        s=new Socket("localhost",40000);
        System.out.println("Begin :) Client");
        input=s.getInputStream();
        out=s.getOutputStream();
        br=new BufferedReader(new InputStreamReader(input));
        pw=new PrintWriter(out);
        in=new Scanner(System.in);
        t1.start();
        t2.start();
    }
    Thread t1=new Thread(new Runnable(){
        @Override
        public void run(){
             str1=in.nextLine();
             pw.println(str1);
             pw.flush();
        }
    });
    Thread t2=new Thread(new Runnable(){
        @Override
        public void run(){
            try {
                str2=br.readLine();
            } catch (Exception e) {}   
            System.out.println(str2);
        }
    });
    public static void main(String[] args) throws Exception {
        Client c=new Client();
        c.create();
    }
}

有没有办法在不使用线程的情况下实现双向通信?

1 个答案:

答案 0 :(得分:0)

while(true){
    str1=in.nextLine();
    pw.println(str1);
    pw.flush();
}

对所有其他run方法语句执行相同操作,代码运行正常