我在玩Sockets并编写了一个测试应用程序,用于向我PC上运行的服务器发送短信并让服务器显示它们。我用Java编写了一个类似的客户端来测试它并且它有效。但现在在Android中,似乎建立了与服务器的连接,但它只收到第一条消息,后续消息不会显示出来。 我想,也许线程只执行一次,但事实并非如此,因为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();
}
}
}
我无法弄清楚导致问题的原因,但肯定是一个愚蠢的错误......
答案 0 :(得分:0)
简而言之,你的代码没有任何意义。