您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
学了个把月基础,终于写出了一个双工通信的控制台版本的聊天室了,废话不说啦,直接上代码:
服务端代码
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: 2680775774@qq.com
* @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: 2680775774@qq.com
* @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
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。