线程实现服务器与客户端互发消息
如果不用多线程来实现服务器与客户端互发消息则当一方发完消息后另一方才可以发,如果用了线程,因为多个线程可以同时执行,只要把发送和接收两个方法放入线程中让他们同时执行就可以实现服务器与客户端互发消息不受限制了
SendThread:
java
public class SendThread implements Runnable{
DataOutputStream dataOutputStream;
public SendThread(Socket socket) throws IOException {
//把Socket传进方法,把要发送的内容送入Socket
dataOutputStream= new DataOutputStream(socket.getOutputStream());
}
@Override
public void run() {
while(true){
Scanner scanner=new Scanner(System.in);
String s=scanner.next();
try {
dataOutputStream.writeUTF(s);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
ReceiveThread:
java
public class ReceiveThread implements Runnable{
DataInputStream dataInputStream;
ReceiveThread(Socket socket) throws IOException {
//把Socket传进方法,得到Socket中的数据
dataInputStream=new DataInputStream(socket.getInputStream());
}
@Override
public void run(){
Thread thread=Thread.currentThread();
while(true) {
try {
String s = dataInputStream.readUTF();
if (thread.getName().equals("客户端")){
System.out.println("服务器说:"+s);
}
if (thread.getName().equals("服务器")){
System.out.println("客户端说:"+s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Server:
java
public static void main(String[] args) {
try {
ServerSocket serverSocket=new ServerSocket(7788);
System.out.println("服务器启动成功");
Socket socket=serverSocket.accept();
System.out.println("有客户端连接到服务器");
SendThread sendThread=new SendThread(socket);
ReceiveThread receiveThread=new ReceiveThread(socket);
Thread tse=new Thread(sendThread);
Thread tre=new Thread(receiveThread,"服务器");
tse.start();
tre.start();
} catch (IOException e) {
e.printStackTrace();
}
}
Client:
java
public static void main(String[] args) {
try {
Socket socket=new Socket("192.168.124.185",7788);
SendThread sendThread=new SendThread(socket);
ReceiveThread receiveThread=new ReceiveThread(socket);
Thread tse=new Thread(sendThread);
Thread tre=new Thread(receiveThread,"客户端");
tse.start();
tre.start();
} catch (IOException e) {
e.printStackTrace();
}
}