针对上一篇博客出现的bug问题,本篇加以修改,采用了多线程技术,不会的铁子们先去看我的多线程技术博客,下面是代码演示:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
* 发送消息的线程
*/
class Send extends Thread{
//与客户端对应的Socket对象
private Socket socket;
public Send(Socket socket){
this.socket = socket;
}
@Override
public void run() {
this.sendMsg();
}
/**
* 发送消息
*/
private void sendMsg(){
try(Scanner scanner = new Scanner(System.in);
//创建向对象发送信息的输出流对象
PrintWriter pw = new PrintWriter(socket.getOutputStream());){
while(true){
String msg = scanner.nextLine();
pw.println(msg);
pw.flush();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
/**
* 接受消息的线程
*/
class Receive extends Thread{
private Socket socket;
public Receive(Socket socket){
this.socket = socket;
}
@Override
public void run() {
this.receiveMsg();
}
/**
* 用于接收对方消息的方法
*/
private void receiveMsg(){
//创建用于接收对方发送消息的流对象
try(BufferedReader br = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));){
while(true){
String msg = br.readLine();
System.out.println("他说:"+msg);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
public class ChatSocketServer {
public static void main(String[] args) {
try(ServerSocket serverSocket = new ServerSocket(8888)){
System.out.println("服务端启动,等待连接。。。。");
Socket socket = serverSocket.accept();
System.out.println("连接成功!");
new Send(socket).start();
new Receive(socket).start();
}catch(Exception e){
e.printStackTrace();
}
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
/**
* 用于发送消息的线程类
*/
class ClientSend extends Thread{
private Socket socket;
public ClientSend(Socket socket){
this.socket = socket;
}
@Override
public void run() {
this.sendMsg();
}
/**
* 发送消息
*/
private void sendMsg(){
//创建Scanner对象
try(Scanner scanner = new Scanner(System.in);
//创建向对方输出消息的流对象
PrintWriter pw = new PrintWriter(this.socket.getOutputStream());){
while(true){
String msg = scanner.nextLine();
pw.println(msg);
pw.flush();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
/**
* 用于接收消息的线程类
*/
class ClientReceive extends Thread{
private Socket socket;
public ClientReceive(Socket socket){
this.socket = socket;
}
@Override
public void run() {
this.receiveMsg();
}
/**
* 用于接收对方消息的方法
*/
private void receiveMsg(){
//创建用于接收对方发送消息的流对象
try(BufferedReader br = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));){
while(true){
String msg = br.readLine();
System.out.println("他说:"+msg);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
public class ChatSocketClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 8888);
System.out.println("连接成功!");
new ClientSend(socket).start();
new ClientReceive(socket).start();
}catch(Exception e){
e.printStackTrace();
}
}
}
非常流畅的聊天模式,铁子们可以去试试