关于Socket的异步的问题~!
我只能写成服务器发一句客户端发一句,,看哪位大神给我改改·,,
我的服务器端代码:
import java.net.*;
import java.io.*;
public class server {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
server s=new server();
}
public server(){
try {
//在9999端口监听
ServerSocket ss=new ServerSocket(9999);
System.out.println("服务器在9999监听。。。");
//等待连接
Socket s=ss.accept();
//接收 客服端发来的消息
InputStreamReader isr=new InputStreamReader(s.getInputStream());
BufferedReader br=new BufferedReader(isr);
//给控制台写的东西给客户端
PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
//接收从控制台输入的信息
InputStreamReader isr2=new InputStreamReader(System.in);
BufferedReader br2=new BufferedReader(isr2);
while(true){
String infoFromClinent=br.readLine();
System.out.println("客户端发来:"+infoFromClinent);
//接收从控制台接收的信息
System.out.println("请输入你对客户端说的话");
String response=br2.readLine();
//把控制台的信息给客服端
pw.println(response);
}
} catch (
IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客服端代码:
import java.net.*;
import java.io.*;
public class client {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
client c=new client();
}
public client(){
try {
//连接服务器
Socket s=new Socket("127.0.0.1",9999);
PrintWriter pw=new PrintWriter(s.getOutputStream(),true);
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
InputStreamReader isr2=new InputStreamReader(s.getInputStream());
BufferedReader br2=new BufferedReader(isr2);
while(true){
System.out.println("请输入你想对服务器说的话:");
//客户端从控制台接收
String info=br.readLine();
pw.println(info);
//接收从服务器发来的话
String res=br2.readLine();
System.out.println("服务器说:"+res);
}
} catch (
UnknownHostException e) {
// TODO Auto-generated catch block