【发布时间】:2021-12-13 16:29:15
【问题描述】:
首先我想介绍一下我目前的代码:
/**
App.java:
**/
package org.example;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class App
{
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(2343);
} catch (IOException e) {
System.err.println("Could not listen on 2343");
}
try {
while (true) {
Socket clientSocket = serverSocket.accept();
try {
new Helper(clientSocket);
} catch (IOException e) {
clientSocket.close();
}
}
} finally {
serverSocket.close();
}
}
}
/**
Helper.java:
**/
package org.example;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class Helper extends Thread {
public static BufferedReader br;
public static BufferedWriter bw;
public static String output = "";
public Helper(Socket socket) throws IOException {
System.out.println("user found");
br = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));
bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8));
start();
}
@Override
public void run() {
while (true) {
try {
bw.write("set");
bw.newLine();
bw.flush();
System.out.println(br.readLine()+"\n"+getId());
} catch (IOException e) {
System.out.println("Client Lost");
break;
}
}
}
}
/**
Cli.java
**/
package org.example2;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
class Cli {
public static void main(String[] argv) throws Exception {
BufferedWriter bw;
Socket clientSocket;
BufferedReader br;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
clientSocket = new Socket("laith.com.au", 2343);
bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream(), StandardCharsets.UTF_8));
br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), StandardCharsets.UTF_8));
while(true){
String input=br.readLine();
bw.write(inFromUser.readLine());
bw.newLine();
bw.flush();
}
}
}
其次,我将显示输出:
App.java
user found
hello world
13
hello world
13
user found
hello world
14
hello world
14
hello world
13
Client Lost
Client Lost
Cli.java (no1 所有用户输入)
hello world
hello world
hello world
hello world
Cli.java (no2 所有用户输入)
hello world
hello world
成绩单:
我启动应用程序:
我启动 Cli 的第一个实例:user found
我在 Cli no1 中输入“hello world”:hello world(换行符)13
我再次在 Cli no1 中输入“hello world”:hello world(换行符)13
我启动第二个 Cli 实例:user found
我在 Cli no2 中输入“hello world”:hello world(换行符)14
我再次在 Cli no2 中输入“hello world”:hello world(换行符)14
我在 Cli no1 中输入“hello world”:hello world(换行符)13
我再次在 Cli no1 中输入“hello world”:
我终止 Cli no1:
我终止 Cli no2:Client Lost(换行符)Client Lost
最后一个问题:
怎么回事,每当我添加另一个客户端连接到服务器时,旧客户端只能在服务器停止响应之前再发送一条消息。
【问题讨论】:
标签: java multithreading sockets server client