我正在製作一個簡單的echo服務器/客戶端應用程序。服務器站點是一個Java應用程序,客戶端站點是一個Android應用程序。Echo服務器/客戶端Java和Android應用程序
客戶端旨在顯示用戶通過Toast消息通過服務器站點發送的內容。但問題在於信息總是延遲。
發送消息後的第一時間,敬酒的消息我是「空」,第二次它表明我發送的第一次...
這讓我很困惑的消息...謝謝你幫助我!
Client:
public class Client extends Activity implements View.OnClickListener {
EditText editText;
Button button;
String string2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client);
editText=(EditText)findViewById(R.id.editText);
button=(Button)findViewById(R.id.button);
button.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.client, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View view) {
Thread thread = new Thread(){
@Override
public void run(){
try {
Socket socket = new Socket("192.168.1.65",1234);
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
DataInputStream dis = new DataInputStream(socket.getInputStream());
dos.writeUTF(editText.getText().toString());
dos.flush();
string2 = dis.readUTF().toString();
dos.close();
dis.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
};
thread.start();
Toast.makeText(this,""+string2,Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Message sent!", Toast.LENGTH_SHORT).show();
}
}
Server:
public class Server {
static Socket socket =null;
public static void main(String[] args) {
Thread thread = new Thread() {
@Override
public void run(){
System.out.println("Server is on ");
try {
ServerSocket serversocket = new ServerSocket(1234);
while(true){
socket = serversocket.accept();
DataInputStream dis = new DataInputStream(socket.getInputStream());
String string = dis.readUTF();
this.sendToClient(string);
System.out.println("Message: "+ string);
dis.close();
socket.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void sendToClient(String str) throws IOException {
OutputStream s = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos = new DataOutputStream(s);
dos.writeUTF(str);
}
};
thread.start();
}
}
我明白你的意思,但我也試圖讓onClick的線程睡眠1秒,通常應該發送字符串。但我仍然有同樣的問題... – Kkr0319 2014-09-23 23:27:42