gpt4 book ai didi

java - 使用 Java 中的套接字编程将数据流从客户端程序(在虚拟机中运行)发送到服务器程序(在主机操作系统上)

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

客户端套接字程序(在 Windows VM 中)按照以下代码生成 1 到 10 之间的整数

public class ClientSocket {

public static void main(String[] args)

{

try{
InetAddress inetAddress = InetAddress.getLocalHost();
String clientIP = inetAddress.getHostAddress();
System.out.println("Client IP address " + clientIP);

Integer dataSendingPort ;
dataSendingPort = 6999 ;

Socket socket = new Socket("192.168.0.32",dataSendingPort);
String WelcomeMessage = " hello server from " + clientIP ;


BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

if(socket.isConnected()){
System.out.println("connection was successful");
}
else{
System.out.println("Error- connection was not successful");
}


for (int x= 0 ; x< 10 ; x++){
bufferedWriter.write(x);
bufferedWriter.flush();
}

bufferedWriter.close();
}
catch (IOException e){
System.out.println(e);
}// catch
finally{

System.out.println("closing connection");

}

} // main

} // class

我的服务器套接字程序作为主机运行在Mac OS上,其代码如下

 public class MyServer {

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


try {
// get input data by connecting to the socket


InetAddress inetAddress = InetAddress.getLocalHost();
String ServerIP = inetAddress.getHostAddress();

System.out.println("\n server IP address = " + ServerIP);

Integer ListeningPort ;
ListeningPort = 6999 ;

ServerSocket serverSocket = new ServerSocket(ListeningPort);

System.out.println("server is receiving data on port # "+ ListeningPort +"\n");

// waiting for connection form client

Socket socket = serverSocket.accept();


if(socket.isConnected()){

System.out.println("Connection was successful");
}
else {
System.out.println("connection was not successful");
}



BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));

Integer s = 0 ;

while (( s = input.read()) >= 0){

System.out.println(input.read());
}
} //try

catch (IOException e)
{
System.out.println(e);

} // catch


} //main
} //socket class

问题是,当我使用 while 循环并在不使用循环的情况下接收第一个值(即 0)时,我收到的输出为 -1。

However, I was able to send a single value from client to server, but how can I send Stream of Values from the client and print it on Server Side.

欢迎提出建议

最佳答案

  • -1表示流结束。
  • 关闭股票的输入或输出流会关闭套接字。
  • socket.isConnected() 在您测试时不可能为 false。
  • input.ready() 并不是对流结束、消息结束、传输结束或任何有用的东西的测试。
  • 不要冲洗循环内部。

关于java - 使用 Java 中的套接字编程将数据流从客户端程序(在虚拟机中运行)发送到服务器程序(在主机操作系统上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45711460/

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