gpt4 book ai didi

java - 接受多个客户端的服务器 - 不工作

转载 作者:行者123 更新时间:2023-11-30 04:40:07 25 4
gpt4 key购买 nike

下面是有一个服务器接受多个客户端连接并响应的代码。服务器能够接收客户端的消息,但客户端未接收服务器消息。我在服务器上使用了多线程概念。我还观察到,除了标有 #### 的行之外,没有任何工作(甚至 println 语句)。可能是该客户端被阻止了..有什么想法吗? 服务器代码: public static void main(String argv[]) 抛出异常 {

     ServerSocket welcomeSocket = new ServerSocket(10000);

while(true)
{

Socket connectionSocket = welcomeSocket.accept();

Thread t = new Thread(new acceptconnection(connectionSocket));
t.start();}}


class acceptconnection implements Runnable{
BufferedReader inFromClient,inn;
DataOutputStream ds;
Socket clientsocket;
//constructor
acceptconnection (Socket socket) throws IOException{
this.clientsocket = socket;
inn = new BufferedReader (new InputStreamReader(System.in));
inFromClient =new BufferedReader(new InputStreamReader(clientsocket.getInputStream()));
ds = new DataOutputStream(clientsocket.getOutputStream());

public void run (){
try {
String clientSentence, inp;
while(( clientSentence = inFromClient.readLine())!=null)
{
System.out.println("from client" + clientSentence);
ds.writeBytes("hi from server");**// THIS DOES NOT WORK**
}

}


Client code:

public static void main(String argv[]) throws Exception
{

Socket clientSocket;
while(true)
{
// clientSock
clientSocket = new Socket("localhost", 10000);
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));

DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

System.out.println("Enter something:");
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');// THIS WORKS - thats why server receives it

**####** modifiedSentence = inFromServer.readLine();**// THIS DOES NOT WORK -client unable to receive**

System.out.println("FROM SERVER: " + modifiedSentence + "remote sock add: "+ clientSocket.getRemoteSocketAddress());

最佳答案

当您在客户端中使用 BufferedReader.readLine() 时,请确保在写出数据时使用换行符:

ds.writeBytes("hi from server\n"); 

并且,正如已经说过的,记得冲洗...

ds.flush();

关于java - 接受多个客户端的服务器 - 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12483936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com