1
我無法連接我的android模擬器到我的電腦。我可以發送信息給android,但發送回它只是失敗。Android通過TCP/IP連接到計算機
這是我到目前爲止有:
public class sendDataToRegion extends AsyncTask<String,Void,List<String> >{
final TextView who = (TextView)findViewById(R.id.txtWho);
final TextView what = (TextView)findViewById(R.id.txtWhat);
final TextView when = (TextView)findViewById(R.id.txtWhen);
final TextView where = (TextView)findViewById(R.id.txtWhere);
final TextView actionTaken = (TextView)findViewById(R.id.txtActionTaken);
final TextView lengthOfTime = (TextView)findViewById(R.id.txtLengthOfTime);
public List<String> dataSend2 = new ArrayList<String>();
@Override
protected List<String> doInBackground(String... params) {
try
{
System.out.println("Mobile Server Program");
String whoString = who.getText().toString();
String whatString = what.getText().toString();
String whenString = when.getText().toString();
String whereString = where.getText().toString();
String actionString = actionTaken.getText().toString();
String lengthString = lengthOfTime.getText().toString();
dataSend2.add(whoString);
dataSend2.add(whatString);
dataSend2.add(whenString);
dataSend2.add(whereString);
dataSend2.add(actionString);
dataSend2.add(lengthString);
int port = 4444;
ServerSocket server = new ServerSocket(port);
Socket socket=server.accept();
DataOutputStream network = new DataOutputStream(socket.getOutputStream());
for(int i = 0; i< dataSend2.size();i++){
network.writeUTF(dataSend2.get(i));
}
}
catch (Exception e) {
Log.e("TCP", "S: Error", e);
}
return dataSend2;
}
protected void onPostExecute() {
System.out.println("Thread Finished " + dataSend2.size());
}
}//End of inner class
它儘可能創建服務器套接字得到,但沒有之後。有人能指出我正確的方向嗎?
感謝
UPDATE
這裏是客戶端:
try
{
String ip = "146.176.230.192";
System.out.println("IP connected");
int port = 4444;
System.out.println("port connected");
// Connect to the server
Socket sock = new Socket(ip, port);
System.out.println("socket created");
// Create the incoming stream to read messages from
DataInputStream network = new DataInputStream(sock.getInputStream());
// Display our address
System.out.println("Address: " + sock.getInetAddress());
String line;
while ((line = network.readUTF()) != null)
{
System.out.println(line);
}
sock.close();
}
catch (IOException ioe)
{
System.out.println("Connection failed");
}
你有一個客戶端連接你的服務器,如果是的話,你可以發佈它的代碼嗎? – njzk2
如果您可以通過手機發送信息,爲什麼要創建服務器套接字?套接字是雙向的,使用相同的套接字。我敢打賭,你的運營商有一個防火牆可以阻止傳入連接,我懷疑你自己有一個IP。 –
你不必綁定你的serversocket嗎? – njzk2