【发布时间】:2017-02-05 04:02:09
【问题描述】:
我正在尝试使用客户端和服务器处理一个简单的项目,其中客户端发送一个字符串,服务器将反转它以发送回客户端。但是,他们都忙于发送和接收消息。几乎可以向您展示我在程序中停止的位置...这是客户端和服务器的控制台输出。
客户
Connecting to server...
S: Connected to server at 4446
You sent Oranges, sending message...
服务器
Waiting for a connection...
Connection received from /127.0.0.1 on port 4446
Waiting for response...
我已经阅读了一些关于您需要如何使用确切的消息输出和输入的信息。因此,就像客户端发送带有新行的输入一样,服务器应该期望读取它。虽然我在我的代码中没有看到这一点,但我的预感是这在某种程度上是问题所在。
我的代码如下...
客户端.java
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client
{
PrintWriter out;
Scanner conIn;
public static void main(String[] args) throws UnknownHostException, IOException
{
Client c = new Client();
c.run();
}
public void run() throws UnknownHostException, IOException
{
System.out.println("Connecting to server...");
Socket connection = new Socket("localhost", 4446); //Connects to server
out = new PrintWriter(connection.getOutputStream());
conIn = new Scanner(connection.getInputStream());
String msg = conIn.nextLine();
System.out.println(msg);
String s = "Oranges";
System.out.println("You sent " + s + ", sending message...");
out.println(s); //STOPS HERE
msg = conIn.nextLine();
System.out.println(msg);
out.flush();
}
}
服务器.java
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server implements Runnable
{
ServerSocket serverSocket;
Scanner in;
PrintWriter out;
Socket connection = null;
public static void main(String[] args)
{
Server s = new Server();
s.run();
}
public void run()
{
try
{
serverSocket = new ServerSocket(4446); //Create server
System.out.println("Waiting for a connection...");
this.connection = serverSocket.accept(); //Accept connection
System.out.println("Connection recieved from " + connection.getInetAddress() + " on port " + connection.getLocalPort());
out = new PrintWriter(connection.getOutputStream()); //Gets output to connection
out.flush();
in = new Scanner(connection.getInputStream()); //Gets input to connection
out.println("S: Connected to server at " + serverSocket.getLocalPort());
out.flush();
System.out.println("Waiting for response...");
String msg = in.nextLine(); //STOPS HERE
System.out.println("Message recieved! Reversing now.");
String rMsg = reverse(msg);
System.out.println("Returning message...");
out.println("S: Your message was: " + msg + " and it is now " + rMsg);
out.flush();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public String reverse(String s)
{
String revS = "";
for(int i = s.length() - 1; i >= 0; i--)
{
revS = revS + s.charAt(i);
}
return revS;
}
}
【问题讨论】:
-
如果在
out.println(s);之后立即执行out.flush();会怎样? -
啊,这似乎奏效了,谢谢!我以为他们每次都想要堆栈或其他东西,您可以在发送一堆输出后进行。但我想这并没有多大意义,哈哈。谢谢
-
在等待数据交叉传输时不能“堆叠”。更好的是使用线程来允许同时输出和输入。
-
哦,好吧,是的,这是设置线程的下一步,以便服务器可以处理多个客户端。
-
@Carson 您可以回答自己的问题并将其标记为已接受,这将向人们表明您不再需要帮助解决您的问题。