使用套接字编程从客户端程序发送数据的流(在VM中运行)到服务器程序(在主机OS)中的Java
问题描述:
客户端插座计划(在windows VM)生成按照下面的代码从1到10整数使用套接字编程从客户端程序发送数据的流(在VM中运行)到服务器程序(在主机OS)中的Java
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
的问题是输出我收到为-1,当我用while循环和接收第一个值,即0而不使用循环。
但是,我能够从客户端发送一个值服务器,但 我怎样才能从客户端发送价值观的流并将其打印在服务器端 。
建议是最欢迎
答
- -1表示流的末尾。
- 关闭股票的输入或输出流会关闭套接字。
-
socket.isConnected()
在您测试时不可能是错误的。 -
input.ready()
不是测试结束的流,或消息的结束,或传输的结束,或真正有用的东西。 - 请勿冲洗内部循环。