我正在開發一個客戶端應用程序,它將當前時間秒發送到另一個充當服務器的應用程序。問題是,當我運行我的應用程序時,它只發送第一條消息(例如,如果它是15:55:02它開始發送02一次又一次)。如何讓我的應用程序連續發送時間秒?通過套接字連續發送數據
這裏是我的代碼:
public class ClientActivity extends Activity
{
private EditText serverIp;
private EditText sendMsg;
private Button connectPhones;
private String serverIpAddress = "";
public static final int SERVERPORT = 8080;
private boolean connected = false;
private Handler handler = new Handler();
private Socket socket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serverIp = (EditText) findViewById(R.id.EditText01);
connectPhones = (Button) findViewById(R.id.myButton);
connectPhones.setOnClickListener(connectListener);
}
private OnClickListener connectListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (!connected) {
serverIpAddress = serverIp.getText().toString();
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
socket = new Socket(serverAddr, SERVERPORT);
connected = true;
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
out.println(seconds);
Log.d("ClientActivity", "C: Sent."+seconds);
} catch (Exception e) {
Log.e("ClientActivity", "S: Error!", e);
}
}
//Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
}
這幫助了我。謝謝! – WWJD