您好,登錄后才能下訂單哦!
學了個把月基礎,終于寫出了一個雙工通信的控制臺版本的聊天室了,廢話不說啦,直接上代碼:
服務端代碼
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。