我想使用TCP从我的手机向我的计算机发送消息。我的电脑是服务器而我的手机是客户端。我可以从手机发送消息到我的电脑,但在输出中,我得到空字符..
我在下方粘贴代码;;
客户端::
public void startApp(){ 尝试{ //与远程服务器建立套接字连接 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) {}
}
}
我的服务器:
public class Main {
/**
* @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);
}
}
}
我的服务器输出;;
服务器已响应
USer说null H
用户说null H null
用户说null H null e
等等
我不应该得到这个空字符,为什么我得到它? 另一件事,我的服务器正在写入流但客户端无法接收,为什么呢?我需要使用单独的线程吗?
先谢谢
答案 0 :(得分:1)
我猜这不是你真正的代码,你的真实代码将str初始化为null。