java tcp编程Demo2—加入多线程

/**
* socket:套接字,它的作用就是能在不同的进程直接进行数据传输。就算不同服务器上的进程也可以进行通信
*
*
*/
public class TcpClient2 {
public static void main(String[] args) throws UnknownHostException, IOException {
//创建client对象
Socket client=new Socket("localhost",9999);
/*BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
//等待用户输入,会阻塞
String msg = br.readLine();
//创建输出流
DataOutputStream dos=new DataOutputStream(client.getOutputStream());
//发送数据给服务端
dos.writeUTF(msg);*/
new Thread(new Send(client)).start();
new Thread(new Recive(client)).start();

 

/**
* 服务端
* @author luoliang
*
*/
public class TcpServer2 {
public static void main(String[] args) {
try {
//创建ServerSocket对象
ServerSocket server=new ServerSocket(9999);
//服务端等待连接 调用这个方法会阻塞
Socket socket = server.accept();
DataInputStream dis=new DataInputStream(socket.getInputStream());
DataOutputStream dos=new DataOutputStream(socket.getOutputStream());
while(true){
String readUTF = dis.readUTF();
System.out.println(readUTF);
String msg="您好";
//响应给客户端
dos.writeUTF(msg);
dos.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

/**
* 接收线程,专门用于接收服务端发送的数据
* @author luoliang
*
*/
public class Recive implements Runnable{
DataInputStream dis=null;
boolean flag=true;
public Recive(Socket client) {
try {
dis=new DataInputStream(client.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
this.flag=false;
}
}
public String recive(){
String readUTF;
try {
readUTF = dis.readUTF();
return readUTF;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
this.flag=false;
}
return "";
}
@Override
public void run() {
while(flag){
String recive = recive();
if(recive==""){
this.flag=false;
return;
}
System.out.println(recive);

}
}

}

/**
* 发送线程 专门用于向服务端发送数据
* @author luoliang
*
*/
public class Send implements Runnable {
DataOutputStream dos=null;
BufferedReader br=null;
boolean flag=true;
public Send(Socket client){
try {
dos=new DataOutputStream(client.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
this.flag=false;
}
}
public void send() throws IOException{
System.out.println("请输入发送给服务器的数据:");
br=new BufferedReader(new InputStreamReader(System.in));
//等待用户输入,会阻塞
try {
String msg = br.readLine();
dos.writeUTF(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
this.flag=false;
dos.close();
br.close();
}
}
@Override
public void run() {
// TODO Auto-generated method stub
while(flag){
try {
send();
} catch (IOException e) {
this.flag=false;
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}



}
}

posted @ 2018-01-03 15:58  罗亮玉  阅读(194)  评论(0编辑  收藏  举报