java实现简易聊天功能
本文实例为大家分享了java实现简易聊天功能的具体代码,供大家参考,具体内容如下
应用客户端和服务端通过控制台的输入输出实现简易聊天功能
思路:
1.创建服务端类ChatServerThread和客户端类ChatClientThradd
2.创建发送类Sendlmpl和接收类Receivelmpl
3.在服务端类中监听8888号端口,并开启发送和接收线程
4.在客户端类中连接8888号端口并开启发送和接收线程
5.在发送类中,开启线程循环,发送用户输入的信息
6.在接收类中,开启线程循环,接收网络发送的数据
代码实现
服务端ChatServerThread
package test;
import java.net.ServerSocket;
import java.net.Socket;
public class ChatServerThread{
//服务端
public static void main(String[] args) throws Exception{
ServerSocket serverSocket = new ServerSocket(8888);
//监听8888号端口
Socket socket = serverSocket.accept();
//开启发送和接收线程
Sendlmpl sendlmpl=new Sendlmpl(socket);
new Thread(sendlmpl).start();
Receivelmpl receivelmpl=new Receivelmpl(socket);
new Thread(receivelmpl).start();
}
}
客户端ChatClientThradd
package test;
import test.Receivelmpl;
import test.Sendlmpl;
import java.net.Socket;
public class ChatClientThradd {
//客户端
public static void main(String[] args) throws Exception{
//连接8888号端口
Socket socket=new Socket("127.0.0.1",8888);
//开启发送和接收线程
Sendlmpl sendlmpl=new Sendlmpl(socket);
new Thread(sendlmpl).start();
Receivelmpl receivelmpl=new Receivelmpl(socket);
new Thread(receivelmpl).start();
}
}
发送类Sendlmpl :
package test;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Sendlmpl implements Runnable {
//发送类
private Socket socket;
public Sendlmpl(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) {
e.printStackTrace();
}
}
}
}
接收类Receivelmpl :
package test;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Receivelmpl implements Runnable{
//接收类
private Socket socket;
public Receivelmpl(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
//循环接收网络发来的信息
while (true) {
try {
InputStream inputStream=socket.getInputStream();
byte [] bytes=new byte[1024];
int z=inputStream.read(bytes);
System.out.println(new String(bytes,0,z));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
相关文章