我正在尝试在ViewRootImpl.java文件中添加客户端套接字。我在一个带有处理程序的新线程中创建套接字,因为我需要在线程之间进行通信。每次调用performTraversal时我都会向Vthread发送一条消息。
ViewRootImpl.java中的客户端代码:
public class Vthread extends Thread{
Viewhandler mViewhandler;
Handler mhandler;
Socket client;
BufferedReader in;
PrintWriter out;
String s;
String line;
Vthread(Viewhandler handler){
mViewhandler = handler;
in = null;
out = null;
s = "hello";
client = null;
}
@Override
public void run(){
Looper.prepare();
try{
client = new Socket("10.0.2.2", 60000);
out = new PrintWriter(client.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(client.getInputStream()));
}catch(IOException e){
e.printStackTrace();
}
mhandler = new Handler(){
@Override
public void handleMessage(Message msg) {
try{
if(out != null && in != null && client != null){
out.println(s);
out.flush();
line = in.readLine();
}
}catch (IOException e) {
e.printStackTrace();
}
}};
Looper.loop();
}
}
主机中的服务器代码:
Socket socket;
ServerSocket server;
SocketAddress sockaddr;
BufferedReader in = null;
PrintWriter out = null;
String line;
String s = "bye";
server = null;
try{
sockaddr = new InetSocketAddress("127.0.0.1", 60000);
server = new ServerSocket();
server.bind(sockaddr);
socket = server.accept();
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
}catch (IOException e) {
e.printStackTrace();
}
try{
System.out.println("connected");
while(!Thread.currentThread().isInterrupted()){
line = in.readLine();
System.out.println(line);
out.println(s);
}
if (server != null ) server.close();
}catch (IOException e) {
e.printStackTrace();
}
接受连接,但服务器未收到来自客户端的任何消息。我发现的一个问题是多个进程可能正在使用套接字。所以我在我的应用程序的内部存储中使用了一个文件来限制套接字到我的应用程序,但问题仍然存在。将套接字限制为我的应用程序的代码:
if(mVthread.mhandler != null) {
try{
if(reader == null) reader = new BufferedReader(new FileReader(file));
Message msg = Message.obtain();
msg.arg1 = 1000;
mVthread.mhandler.sendMessage(msg);
}catch(Exception e){
e.printStackTrace();
}
}
修改
问题是客户端套接字发送消息但服务器没有收到消息。双方都在接收功能中被阻止。对我做错了什么的想法?