JAVA全系列 教程
3762个小节阅读:7090.4k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
创建客户端
xxxxxxxxxx
/**
* 用于发送消息的线程类
*/
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();
}
}
}