查看本章节
查看作业目录
需求说明:
应用客户端和服务端通过 Eclipse 控制台的输入和显示实现简易的聊天功能
实现思路:
- 创建 Java 项目,在项目中创建服务端类 ChatServerThread 和客户端类 ChatClientThread
- 创建 Java 项目,在项目中创建发送类 SendImpl 和接收类 ReceiveImpl
- 在ChatServerThread 类中,监听 8888 端口,并开启发送和接收线程
- 在ChatClientThread 类中,连接 8888 端口,并开启发送和接收线程
- 在SendImpl 类中,开启线程循环,发送用户输入的信息
- 在 ReceiveImpl 类中,开启线程循环,接收网络发送过来的数据
实现代码:
服务端类 ChatServerThread
import java.net.Socket;
public class ChatServerThread {
public static void main(String[] args) throws Exception {
Socket socket = new Socket("127.0.0.1", 8888);
SendImpl sendImpl = new SendImpl(socket);
// 发送的线程
new Thread(sendImpl).start();
// 接收的线程
ReciveImpl reciveImpl = new ReciveImpl(socket);
new Thread(reciveImpl).start();
}
}
客户端类 ChatClientThread
import java.net.ServerSocket;
import java.net.Socket;
public class ChatClientThread {
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(8888);
Socket socket = serverSocket.accept();
SendImpl sendImpl = new SendImpl(socket);
new Thread(sendImpl).start();
ReciveImpl reciveImpl = new ReciveImpl(socket);
new Thread(reciveImpl).start();
}
}
发送类 SendImpl
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class SendImpl implements Runnable {
private Socket socket;
public SendImpl(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
Scanner scanner = new Scanner(System.in);
while (true) {
try {
OutputStream outputStream = socket.getOutputStream();
String string = scanner.nextLine();
outputStream.write(string.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
接收类 ReceiveImpl
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class ReciveImpl implements Runnable {
private Socket socket;
public ReciveImpl(Socket socket) {
this.socket = socket;
// TODO Auto-generated constructor stub
}
@Override
public void run() {
while (true) {
try {
InputStream inputStream = socket.getInputStream();
byte[] b = new byte[1024];
int len = inputStream.read(b);
System.out.println("收到消息:" + new String(b, 0, len));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}