【发布时间】:2017-03-20 21:15:50
【问题描述】:
我的代码有问题 我创建了一个应用程序,通过单击
向/从服务器发送和接收消息按钮
发送消息效果很好 但是当收到它并没有显示任何东西 我希望应用程序在与服务器发送和接收和显示消息的通信期间向我显示消息,因为我只是注意到在通信期间应用程序无法显示任何内容(吐司或更改 TextView/EditText 的文本或任何内容)期望只是接收不显示的变量数据 但我需要应用程序在与服务器通信期间做很多事情(显示吐司和打开对话框等)
点击代码:
EditText nom ; //nom= (EditText) findViewById(R.id.user); is in Oncreate methode
String name,check;
String check;
public void click(View view) {
name=nom.getText().toString();
Thread t=new Thread(new Runnable() {
@Override
public void run() {
Socket s;
try {
s = new Socket(ipadresse,Integer.parseInt(por));
//those 2 (ip,por) are in methode (oncreate)
DataOutputStream dos=new DataOutputStream(s.getOutputStream());
//emission just du nom (un exemple)
dos.writeUTF(String.valueOf(name));
//sending message
//recieving a message :
DataInputStream dis=new DataInputStream(s.getInputStream());
check=dis.readUTF();
//i've tried this command but not work :/
//BufferedReader read=new BufferedReader(
//new InputStreamReader(s.getInputStream()));
//check= read.readLine();
Log.i("message", "message recieved : "+check);
//logcat show me that the message recieved but toast doesn't
//( in fact i didn't want toast i want to show a dialog box
//but as a simple example i used toast)
Toast.makeText(login.this, check, Toast.LENGTH_SHORT).show();
dos.flush();
//dis.close();
dos.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
这里是服务器代码:
public static void main(String[] args) {
Thread t;
t = new Thread(new Runnable() {
@Override
public void run() {
try {
ServerSocket s = new ServerSocket(8080);
System.out.println("connecting ... ");
System.out.println("-------------------");
while(true)
{
Socket s1= s.accept();
DataInputStream dis=new DataInputStream(s1.getInputStream());
DataOutputStream dos=new DataOutputStream(s1.getOutputStream());
String message;
message=dis.readUTF();
System.out.println(message);
//this message does't displayed in the app (i've edited the program just to simplify it)
dos.writeUTF("hello");
dis.close();
s1.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t.start();
}
【问题讨论】:
-
你在哪里告诉客户端继续监听套接字?
-
我只是使用 DataInputStream 来接收消息,因为我使用 DataOutputStream 来发送它
-
Toast() 会让你的客户端应用崩溃不是吗?你不能在 runnable() 的 run() 中使用 Toast。
-
我不能使用 toast 也不能编辑 textview 的文本
-
我需要在不停止交流的情况下显示消息并做其他事情(就像聊天什么的)
标签: java android sockets server client