繁体   English   中英

为什么我的输出中收到null?

[英]Why I am receiving null in my output?

我想使用TCP从手机发送消息到我的计算机。我的计算机是服务器,我的电话是客户端。 我可以将消息从手机发送到计算机,但是在输出中,我得到了空字符..

我将代码粘贴到下面;

客户::

public void startApp(){try {//与远程服务器建立套接字连接streamConnection =(StreamConnection)Connector.open(connectString);

  // create DataOuputStream on top of the socket connection
  outputStream = streamConnection.openOutputStream();
  dataOutputStream = new DataOutputStream(outputStream);

  // send the HTTP request
  dataOutputStream.writeChars("Hello");
  dataOutputStream.flush();

  // create DataInputStream on top of the socket connection
  inputStream = streamConnection.openInputStream();
  dataInputStream = new DataInputStream(inputStream);

  // retrieve the contents of the requested page from Web server
  String test="";
  int inputChar;
  System.out.println("Entering read...........");
  while ( (inputChar = dataInputStream.read()) != -1) {
     // test=test+((char)inputShar);
    results.append((char) inputChar);
  }
  System.out.println("Leaving read...........");
  // display the page contents on the phone screen
  //System.out.println(" Result are "+results.toString());
  System.out.println("   ");
  resultField = new StringItem(null, results.toString());
  System.out.println("Client says "+resultField);
  resultScreen.append(resultField);
  myDisplay.setCurrent(resultScreen);

} catch (IOException e) {
  System.err.println("Exception caught:" + e);
} finally {
  // free up I/O streams and close the socket connection
  try {
    if (dataInputStream != null)
      dataInputStream.close();
  } catch (Exception ignored) {}
  try {
    if (dataOutputStream != null)
      dataOutputStream.close();
  } catch (Exception ignored) {}
  try {
    if (outputStream != null)
      outputStream.close();
  } catch (Exception ignored) {}
  try {
    if (inputStream != null)
      inputStream.close();
  } catch (Exception ignored) {}
  try {
    if (streamConnection != null)
      streamConnection.close();
  } catch (Exception ignored) {}
}

}

我的服务器:

公共班级主要{

/**
 * @param args the command line arguments
 */
public static void main(String[] args)  {
    // TODO code application logic here
  try{
      ServerSocket sck=new ServerSocket(880);
      Socket client=sck.accept();
      InputStream inp= client.getInputStream();
      int  i;
      OutputStream out=client.getOutputStream();
      out.write("Testing ".getBytes());
      System.out.println("Server has responded          ");
      String str="";
      while((i=inp.read())!=-1){

          str=str+((char) i);
           System.out.println("USer says "+ str);
      }

  }
  catch(Exception e){
      System.out.println("Error "+e);
  }

}

}

我对服务器的输出;

服务器已响应
用户说空H空用户说空H空用户说空H空e等

我不应该得到这个空字符,为什么要得到它? 另一件事,我的服务器正在写入流,但是客户端无法接收该消息,为什么?我需要为此使用单独的线程吗?

感谢在副词

我想这不是您的真实代码,并且您的真实代码将str初始化为null。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM