[英]Android Socket Connection loss?
I´m playing around with Sockets and wrote a test app to send text messages to a server running on my PC and have the server display them. 我在玩Sockets,编写了一个测试应用程序,可将文本消息发送到PC上运行的服务器,并让服务器显示这些消息。 I wrote a similar client in Java to test it and it worked.
我用Java编写了一个类似的客户端来对其进行测试,并且它可以正常工作。 But now in Android, it seems to establish a connection to the server, but it only recieves the first message and subsequent messages won´t show up.
但是现在在Android中,似乎可以建立与服务器的连接,但是它只能接收第一条消息,而后续消息将不会显示。 I thought, maybe the thread is only executing once, but that´s not the case since logcat recognizes the button presses.
我以为,也许线程只执行一次,但事实并非如此,因为logcat可以识别按钮的按下。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText enter = (EditText) findViewById(R.id.editText1);
final Button button = (Button) findViewById(R.id.button);
final String fromUser = null;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable(){
@Override
public void run(){
PrintWriter out = null;
BufferedReader in = null;
Socket clientSocket = null;
try {
clientSocket = new Socket("192.168.178.41", 5959);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
Log.d("---","cant make a connection");
}
String fromUser = enter.getText().toString();
if (fromUser != null) {
System.out.println("Client: " + fromUser);
out.println(fromUser);
}
}
}).start();
}
});
}
}
public class Server {
public static void main(String[] args) {
System.out.println("Starting server!");
PrintWriter out = null;
BufferedReader in = null;
try{
ServerSocket serverSocket = new ServerSocket(5959);
Socket clientSocket = serverSocket.accept();
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Established a connection with a user!");
} catch (IOException e) {
e.printStackTrace();
}
String inputLine;
String outputLine = "Hey Client from Server!";
out.println(outputLine);
try {
while ((inputLine = in.readLine()) != null) {
out.println(inputLine);
System.out.println("Client: " + inputLine);
if (inputLine.equals("quit"))
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I cant figure out what is causing the problem, but its for sure a silly mistake... 我不知道是什么原因引起的,但是肯定是一个愚蠢的错误...
In short your code makes no sense whatsoever. 简而言之,您的代码毫无意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.