客户端和服务端都分别需要两个线程,一个用来进行消息发送,一个用来进行消息接受。
- 客户端:
package com.jay.test;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class Client {
private Socket socket;
//初始化,连接目的服务器的端口
public Client(){
try {
socket=new Socket("localhost",13);
} catch (IOException e) {
e.printStackTrace();
}
//启动接受信息的线程
GetMsgFromServer getMsgFromServer=new GetMsgFromServer(socket);
new Thread(getMsgFromServer).start();
}
//发送信息的方法
public void start(){
Scanner scanner=new Scanner(System.in);
try {
PrintWriter printWriter=new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"),true);
//持续发送信息
while (true){
String msg=scanner.next();
printWriter.println(msg);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[]args){
Client client=new Client();
client.start();
}
}
//接受信息的线程
class GetMsgFromServer implements Runnable{
private Socket socket;
public GetMsgFromServer(Socket socket){
this.socket=socket;
}
@Override
public void run() {
try {
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
String s;
while((s=bufferedReader.readLine())!=null)
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
}
}
- 服务端:
package com.jay.test;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
private ServerSocket serverSocket;
//初始化服务器信息,绑定端口
public Server(){
try {
serverSocket=new ServerSocket(13);
} catch (IOException e) {
e.printStackTrace();
}
}
public void start(){
while(true){
try {
Socket socket=serverSocket.accept();
//接受信息的线程
new Thread(new ServerThread(socket)).start();
String s;
Scanner scanner=new Scanner(System.in);
PrintWriter printWriter=new PrintWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8"),true);
while(true){
s=scanner.next();
printWriter.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args){
Server server=new Server();
server.start();
}
}
class ServerThread implements Runnable{
private Socket socket;
public ServerThread(Socket socket){
this.socket=socket;
}
@Override
public void run() {
try {
//获取对应的缓冲输入流
BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream(),"utf-8"));
String s;
//持续接受信息
while((s=bufferedReader.readLine())!=null)
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
效果
-
服务端:
-
客户端:
来源:CSDN
作者:Jayicee
链接:https://blog.csdn.net/SCUTJAY/article/details/104109023