gpt4 book ai didi

java - 客户端服务器应用程序不工作

转载 作者:行者123 更新时间:2023-12-02 06:06:40 24 4
gpt4 key购买 nike

我正在尝试编写一个简单的客户端/服务器 Echo 应用程序,我的客户端似乎正在发送输入,但服务器似乎没有接收它并将其发回。

这是服务器:

import java.io.*;
import java.net.*;

public class Server
{
public static void main(String args[]) throws Exception
{
int port = 2000;
ServerSocket serverSocket;
Socket client;

BufferedReader is = null;
BufferedWriter os = null;

serverSocket = new ServerSocket(port);
System.err.println("Server established on port " + port);

client = serverSocket.accept();
System.err.println("Client connected");

is = new BufferedReader(
new InputStreamReader(client.getInputStream()));
os = new BufferedWriter(
new OutputStreamWriter(client.getOutputStream()));
System.err.println("Server established on port " + port);

String message = "";

while((message = is.readLine()) != null)
{
System.err.println("Messaged received " + message);
os.write(message);
}

is.close();
os.close();
serverSocket.close();
}
}

然后,客户端看起来像这样:

import java.io.*;
import java.net.Socket;

public class Client
{
public static void main(String args[]) throws Exception
{
String host = "localhost";
int port = 2000;
Socket socket;

socket = new Socket(host, port);

BufferedReader is = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
BufferedWriter os = new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream()));
System.err.println("Connected to " + host + " on port " + port);

BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));

String input = "";

while((input = br.readLine()) != null)
{
System.out.println("Sending " + input);
os.write(input);
System.out.println("Receiving " + is.read());
}

is.close();
os.close();
socket.close();
}
}

我错过了什么,我确信我忽略了一些简单的事情。

最佳答案

在客户端中,尝试使用最后一个换行符编写消息:

os.write(input+"\n");

(或者也调用newLine())

这是因为服务器正在逐行读取。

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

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