-3
我想讓客戶端連接到服務器發送數據(請求)和接收數據(回覆)。Android中的TCP客戶端
我有TCP服務器(PC/Ubuntu Linux操作系統):
public class TCPClient {
public static void main(String argv[]) throws Exception {
System.out.println("Client started.");
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 5555);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
和TCP客戶端(安卓):
public class TCPClient2 extends AsyncTask<String, Integer, Boolean> {
Socket clientSocket;
String sentence;
String modifiedSentence;
DataOutputStream outToServer;
BufferedReader inFromServer;
public TCPClient2() throws IOException {
}
public void close(){
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
protected Boolean doInBackground(String... arg0) {
try {
Log.d("TcpClient", "Client started.");
clientSocket = new Socket("192.168.1.8", 5555);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = "getTemp";
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
Log.d("TcpClient","FROM SERVER: " + modifiedSentence);
clientSocket.close();
} catch (SocketException e) {
e.printStackTrace();
Log.d("TcpClient", "Error: " + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
Log.d("TcpClient","Error: " + e.getMessage());
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
Log.d("TcpClient", String.valueOf(values));
}
}
權限:在ADM
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
結果:
01-14 20:22:17.721: D/TcpClient2(23925): Click!!!
01-14 20:31:35.861: D/TcpClient(23925): Client started.
01-14 20:31:35.951: D/TcpClient(23925): Error: failed to connect to 192.168.1.8 (port 5555): connect failed: ECONNREFUSED (Connection refused)
它不工作;(
'無法寫入正確的代碼'不是問題描述。 – EJP