简体   繁体   English

Java:TCP套接字连接。 接收null / readline()的客户端返回null

[英]Java: TCP socket connection. Client receiving null/readline() returns null

I am new to java TCP socket. 我是java TCP套接字的新手。 I tried to implement a server and a client. 我试图实现一个服务器和一个客户端。 So the server should check input (do something) and send string to client. 所以服务器应检查输入(做某事)并将字符串发送到客户端。 The client should send string to the server and look for an input string from the server (and do something). 客户端应该将字符串发送到服务器并从服务器中查找输入字符串(并执行某些操作)。 Both should loop checking and sending all the time if something new is available. 如果有新的可用内容,它们都应该循环检查并一直发送。 The client can send data to the server, the server receives it an can display/process this data. 客户端可以将数据发送到服务器,服务器接收它可以显示/处理该数据。 But the data from the server isn't displayed by the client. 但是客户端不显示来自服务器的数据。 Can someone tell me why the client isn't receiving the string from the server? 有人能告诉我为什么客户端没有从服务器接收字符串? Any better ideas to do endless loop? 有没有更好的想法做无限循环? There will be only one client and one server. 将只有一个客户端和一个服务器。

 while true:
 server out------>  send String----->   in client            
        in<-----  sent String <------   out

this is the simplified server part: 这是简化的服务器部分:

public class MainActivity extends Activity {
Socket client;
ServerSocket server;
int serverport = 54321;
String inputData = null;
BufferedReader in;
PrintWriter out;
String outputData;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(setupConnection).start();    
}

private Runnable setupConnection = new Thread() {
public void run() {
try {
server = new ServerSocket(serverport);
    while (true) {
    client = server.accept();
    in = new BufferedReader(new InputStreamReader(client.getInputStream()));
    out = new PrintWriter(client.getOutputStream(), true);
    inputData = in.readLine();
    InputStream inStream = new ByteArrayInputStream(inputData.getBytes());
    in.close();
        if (inputData != null) {
        System.out.println(TAG + "-----Incoming Message---- " + inputData);
        //this is working String is shown           
        }       }
    out.write("nothing to do?");
    out.flush();
    out.close();
    }

} catch (SocketException e) {
Log.v(TAG, "SocketException: " + e);
e.printStackTrace();
} catch (IOException e) {
Log.v(TAG, "IOException: " + e);
e.printStackTrace();
}
}

the simplified client looks like this: 简化的客户端看起来像这样:

public class testClass {
public static void main(String[] args) throws IOException, InterruptedException {
Socket socket = null;
String host = "127.0.0.1";
int port = 54321;
PrintWriter out = null;
BufferedReader in = null;

while (true) {
try {
    socket = new Socket(host, port);
    out = new PrintWriter(socket.getOutputStream(), true);
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
    System.out.println(TAG + "Error: " + e);
    System.err.println("Don't know about host: localhost.");
    System.exit(1);
} catch (IOException e) {
    System.out.println(TAG + "Error: " + e);
    System.err.println("Couldn't get I/O for " + "the connection to: localhost.");
    System.exit(1);
}

out.println("Hello, is it me you're looking for...");
out.flush();


String input = in.readLine();
System.out.println("Input: " + input);

in.close();
out.close();

}
}
}

If readLine() returns null,the peer has closed the connection, and you must do likewise. 如果readLine()返回null,则对等体已关闭连接,您必须这样做。 And stop reading. 并停止阅读。

if you want implement this code in android , you faces many problems: you can find the solution in this link: Post JSON in android 如果你想在android中实现这个代码,你会遇到很多问题:你可以在这个链接中找到解决方案: 在android中发布JSON

in the following code may be fix this problem: 在以下代码中可能会解决此问题:

    HttpPost post = new HttpPost("http://xxxxxx");
    DefaultHttpClient httpClient = new DefaultHttpClient();
    post.setEntity(new ByteArrayEntity(json.toString().getBytes()));
    HttpResponse response = httpClient.execute(post);
    return EntityUtils.toString(response.getEntity());

} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    System.out.println(">>>>>>>" + e.getMessage());
} catch (ClientProtocolException e) {
    e.printStackTrace();
    System.out.println(">>>>>>>" + e.getMessage());
} catch (IOException e) {
    e.printStackTrace();
    System.out.println(">>>>>>>" + e.getMessage());
}

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

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