【发布时间】:2015-07-01 13:26:14
【问题描述】:
我正在尝试将客户端系统的详细信息发送到服务器系统,但服务器没有收到任何内容。一旦到达第一行,它就会停止打印。有人帮我解决这个问题。
//服务器
void connect_clients() throws ClassNotFoundException, InterruptedException
{
try {
ServerSocket listener = new ServerSocket(7700);
jButton1.setText("Server Running!");
jButton1.setEnabled(false);
ObjectInputStream ois; // = new ObjectInputStream(socket.getInputStream());
while (true) {
socket = listener.accept();
socketList.add(socket);
ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message Received: " + message); */*/*this is not printing everything
}
}
catch(IOException ex)
{
JOptionPane.showMessageDialog(null, ex);
}
}
//客户端
void connect_server() throws IOException
{
try {
// TODO code application logic here
String serverAddress = JOptionPane.showInputDialog(
"Enter IP Address of a machine that is\n" +
"running the date service on port 9090:");
s = new Socket(serverAddress, 7700);
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream ois = null;
BufferedReader input;
String answer;
while(true){
input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
DataOutputStream dOut = new DataOutputStream(s.getOutputStream());
answer = input.readLine();
System.out.println(answer);
if(answer != null)
{
oos.reset();
String line = "";
String command = "powershell.exe Get-ItemProperty HKLM:\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\* | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | \n" +
"Format-Table –AutoSize";
// Executing the command
Process powerShellProcess = Runtime.getRuntime().exec(command);
// Getting the results
powerShellProcess.getOutputStream().close();
System.out.println("Standard Output:");
BufferedReader stdout = new BufferedReader(new InputStreamReader(
powerShellProcess.getInputStream()));
while ((line = stdout.readLine()) != null) {
byte[] mybytearray = new byte[(int) line.length()];
oos.writeObject(mybytearray);
}
stdout.close();
System.out.println("Standard Error:");
BufferedReader stderr = new BufferedReader(new InputStreamReader(
powerShellProcess.getErrorStream()));
while ((line = stderr.readLine()) != null) {
oos.writeObject(line);
System.out.println("fdg"+line);
//printing the output to a file --start
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)))) {
out.println(line);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, e);
}
}
stderr.close();
System.out.println("Done");
}
}
}
catch (ConnectException e) {
JOptionPane.showMessageDialog(null, e);
}
catch (SocketException e) {
JOptionPane.showMessageDialog(null, e);
}
}
【问题讨论】:
-
您将
s.getOutputStream()包装在ObjectOutputStream和DataOutputStream中。这让我觉得这是一个非常糟糕的主意。考虑到您从未使用过dOut,这可能不是问题,但这仍然是个坏主意... -
而你在循环中这样做,这使得情况变得更糟。在循环顶部只打开这些流一次。
-
那么正确的方法和解决方案是什么?
标签: java string client server lan