gpt4 book ai didi

Java套接字无法正确显示收到的输入

转载 作者:行者123 更新时间:2023-11-30 08:43:25 24 4
gpt4 key购买 nike

我正在尝试让 Java 客户端程序接收来自服务器的输入。但是代码无法获取输入并将其打印出来。它编译得很好。问题是接收到的输入没有打印到控制台。这是创建套接字的部分

Socket ss = new Socket(host,port);
String input;
Scanner in;
in = new Scanner(ss.getInputStream());
while(true)
{
input = in.next();
System.out.print(input + "\n");
if("quit".equalsIgnoreCase(input));
{
in.close();
ss.close();
return;
}
}

这是我所有的代码

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

public class connect
{
static int port;
static String host;
public static void start(String host, int port)
{
while(true)
{
try
{
Socket ss = new Socket(host,port);
String input;
Scanner in;
in = new Scanner(ss.getInputStream());
while(true)
{
input = in.next();
System.out.print(input + "\n");
if("quit".equalsIgnoreCase(input));
{
in.close();
ss.close();
return;
}
}
}
catch (UnknownHostException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
String check;
do
{
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);

System.out.println("Hello, welcome to the client");
String banner = "-";
int x = 0;

while(x<60)
{
banner += "-";
x++;
}
System.out.println(banner);
System.out.print("\n\nPlease Enter the ip address to connect to\n>>");
host = sc.next();
System.out.println("We are connecting to " + host);
System.out.print("\n" + banner + "\nEnter the port\n>>");
port = sc.nextInt();
System.out.println("Connecting to\nhost->" + host + "\nport->" + port);
System.out.println("Enter 'Done' to continue, any to reset");
check = sc.next();
}while(!"Done".equals(check));
start(host,port);
System.out.println("Finished");
}
}

服务器是用python做的,只是为了测试一下。这是python代码

import socket
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind(('',443))
s.listen(1)
conn,addr=s.accept()
conn.send("Hello")
conn.send("World")

这段代码在客户端的输出应该是

-->你好

-->世界

应该打印 Hello 然后打印 World 然后等待更多输入。但是,在服务器关闭之前不会显示输出。服务器关闭时显示 HelloWorld

最佳答案

来自 send 的 python 文档:

Applications are responsible for checking that all data has been sent; if only some of the data was transmitted, the application needs to attempt delivery of the remaining data.

使用sendall如果您不想担心检查数据是否已发送,因为它会继续尝试传递数据,直到所有数据都已传递或直到发生错误。

Scanner 将根据分隔符(我相信默认情况下是一个空格)对数据进行标记。 Scanner#next()只有达到指定的分隔符才会返回数据:

A complete token is preceded and followed by input that matches the delimiter pattern.

确保在接收数据时考虑到这一点(您发送的数据需要在某处指定分隔符,用于扫描仪的分隔符)。您可以通过 Scanner#useDelimiter(String) 更改分隔符或 Scanner#useDelimiter(Pattern)

关于Java套接字无法正确显示收到的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34280388/

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