【问题标题】:Having problems with .getInputStream().getInputStream() 有问题
【发布时间】:2015-10-22 14:58:27
【问题描述】:

我正在尝试对 TCP 聊天服务器进行编程,但在使用 .getInputStream() 和 .getOutputStream() 方法时遇到了困难,编译器说“找不到符号方法 .getInputStream()。 这是我的代码,我还没有进步很多:

import java.net.*;
import java.io.*;
public class Server {
 public static void Server (String[] args) {
  ServerSocket SS1 = null;
  DataOutputStream DOS1 = null;
  DataInputStream DIS1 = null; //Setting the values to null
  try {
   SS1 = new ServerSocket(5000); //setting the socket SS1 to port 5000 and creating an instance
   Socket clientSocket = SS1.accept(); //accepting the connection request
   DOS1 = new DataOutputStream(SS1.getOutputStream());
   DIS1 = new DataInputStream(SS1.getInputStream()); //creating output and input streams
  }
  catch (Exception e){
   System.err.println("Error!");
  }
 }
}

如果这是问题所在,我在 Windows 7 上使用 BlueJ。 此外,我似乎无法找到关于数据流或“老式”套接字如何工作的好的解释,所以如果有人知道我在哪里可以得到这些,将不胜感激。 :)

~阿隆。

【问题讨论】:

  • 你正在使用ServerSocket 你应该使用clientSocket.get****() 他们属于Socket 类而不是ServerSocket

标签: java sockets datainputstream dataoutputstream


【解决方案1】:

你必须打电话:

clientSocket.getOutputStream()
clientSocket.getInputStream()

在您的 DataOutput-/DataInputStream 构造函数中。

【讨论】:

  • 那么,像这样吗? DOS1 = new DataOutputStream(clientSocket.getOutputStream()); DIS1 = new DataInputStream(clientSocket.getInputStream());
【解决方案2】:

您错误地在Socket(连接到服务器的客户端)中使用了ServerSocket

试试这个:

clientSocket.getOutputStream() clientSocket.getInputStream()

【讨论】:

  • 谢谢。我也尝试添加if ((DIS1 != null) && (DOS1 != null) && (SS1 != null)){ System.out.println("Connection is not- null."); } else { System.out.println("Connection is null!"); },但除了毫无例外地接受输入之外,它似乎没有做任何事情。到底是怎么回事?另外,现在我正在尝试创建一个客户端,getOutputStream() 给出了编译器错误 "non-static method getOutputStream() cannot be referenced from a static context" 。我现在该怎么办?
  • @AlonandIdan 您不需要检查 null,因为如果出现任何问题,它会抛出 exception。它们不应该也永远不会为空。
  • @AlonandIdan 现在getOutputStream()Socket 类的方法,因此您需要使用该类型的对象调用它。所以在上面的代码中你需要做clientSocket.getOutputStream(),这样就可以了。如您所见,clientSocket 是一个 Socket 对象
  • 在继续我的代码之前,我只想知道是否存在 连接。
  • 那么我是否需要在服务器客户端中都使用clientSocket.getOutputStream()?我试过了,它给了cannot find symbol- variable clientSocket
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-18
  • 2011-06-22
  • 1970-01-01
相关资源
最近更新 更多