客户端:
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ChatClient {
public static void main(String[] args) {
//使用线程池
ExecutorService service=Executors.newFixedThreadPool(3);
try {
Socket socket=new Socket("127.0.0.1", 8888);
service.execute(new SendTread(socket));
service.execute(new ReveicerThread(socket));
//new SendTread(socket).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务端:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ChatServer {
public static void main(String[] args) {
//使用线程池
ExecutorService service=Executors.newFixedThreadPool(3);
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(8888);
Socket socket=serverSocket.accept();
service.execute(new SendTread(socket));
service.execute(new ReveicerThread(socket));
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端线程:
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
/*
* 一个客户端与一个服务端进行聊天。
* 1:接收数据,
* 2:发送数据。
* 同时进行。:线程。 一个线程负责接收数据,一个线程负责发送数据。
*/
public class SendTread extends Thread {
Scanner sc = new Scanner(System.in);
String str = null;
// 定义构造方法获取套接
private Socket socket;
public SendTread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
// 获得输出管道。
OutputStream os = null;
try {
os = socket.getOutputStream();
while (true) {
System.out.println("请输入发送的数据");
str = sc.nextLine();
if("".equals(str)||str==null||"886".equals(str)){
break;
}
os.write(str.getBytes());
os.write("\r\n".getBytes());
//如果接收端是用bufferReader来读的话要加上回车换行符
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务端线程:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Scanner;
public class ReveicerThread extends Thread{
Scanner sc=new Scanner(System.in);
String str=null;
private Socket socket;
public ReveicerThread(Socket socket) {
this.socket = socket;
}
public void run() {
InputStream is=null;
BufferedReader br=null;
try {
is=socket.getInputStream();
br=new BufferedReader(new InputStreamReader(is));
String ip=socket.getInetAddress().getHostAddress();
int port=socket.getPort();
//如果是用bufferReader来读的话,发送端要加上回车换行符
while(true){
str=br.readLine();
if(str==null||socket==null||"".equals(str)){break;}
System.out.println("ip "+ip+" : 端口"+port+str);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
转载于:https://my.oschina.net/u/2541146/blog/596451