我的代码有问题 我创建了一个应用程序,通过单击
向服务器发送消息并从服务器接收消息按钮
发送消息非常好 但收到它时并没有向我显示任何东西 我希望应用程序在与服务器发送和接收和显示消息的通信过程中向我显示消息,因为我只是注意到在通信期间应用程序无法显示任何内容(吐司或更改TextView / EditText或任何内容的文本)期望只是接收没有显示的变量数据 但我需要应用程序在与服务器通信期间做很多事情(显示吐司和打开对话框等..)
代码onclick:
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();
}
答案 0 :(得分:-1)
也许来自您服务器的消息会延迟返回(不是实时)。 尝试make循环:
boolean getmessage = false;
while(!getmessage){
try{
check=dis.readUTF();
}
catch(Exception e){
Log.d("dis", e.getMessage());
}
if(check != null){
getmessage = true;
makeToast("23");
}
}