学了个把月基础,终于写出了一个双工通信的控制台版本的聊天室了,废话不说啦,直接上代码:
服务端代码
package com.zijiemaedu.socketdemo;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
* @author: Mr-zhang
* @create: 2019-05-30 09:48
* @emall: [email protected]
* @program: thread-demo
* @ClassName: Server
* @purpose:
*/
public class Server {
public final static int PORT = 8888; // 服务端监听端口
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(PORT); // 服务端对象
Socket socket = server.accept(); // 等待客户端链接(导致程序阻塞)
InputStream inputStream = socket.getInputStream();// 获取客户端发送过来的数据流
OutputStream outputStream = socket.getOutputStream();// 获取客户端发送过来的数据流
// 将流进行转换
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
// 向客户端输出消息
new Thread(new Runnable() {
@Override
public void run() {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入您想发送给客户端的消息:");
String line = scanner.next();
while (line != null) {
try {
writer.write(line);
writer.newLine();
writer.flush();
System.out.println("请输入您想发送给客户端的消息:");
line = scanner.next();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
socket.close();
server.close();
}
}
客户端代码:
package com.zijiemaedu.socketdemo;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
/**
* @author: Mr-zhangY
* @create: 2019-05-30 09:57
* @emall: [email protected]
* @program: thread-demo
* @ClassName: Client
* @purpose:
*/
public class Client {
private final static String HOST = "localhost";
private final static int PORT = Server.PORT;
public static void main(String[] args) throws IOException {
Socket socket = new Socket(HOST, PORT); // 创建客户端socket
OutputStream output = socket.getOutputStream();
InputStream inputStream = socket.getInputStream(); // 获取服务端输入过来的消息流
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
new Thread(() -> {
try {
while (true) {
String message = reader.readLine();
System.out.println("服务端响应了: " + message);
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
while (input != null) {
if ("q".equals(input)) {
break;
}
writer.write(input);
writer.newLine();
writer.flush();
input = scanner.next();
}
writer.close();
socket.close();
}
}
有需要交流软件开发的同学可以加我qq哦,2680775774
原文地址:https://blog.51cto.com/12958268/2402963
时间: 2024-11-03 21:04:56