我有一个简单的服务器:
public class MyServer {
public static void main(String[] args) throws IOException {
ServerSocket ss;
Socket client;
ss = new ServerSocket(8888);
System.out.println("Server socket created");
client = ss.accept();
Scanner in = new Scanner(client.getInputStream());
while(in.hasNextLine()) {
System.out.println(in.nextLine());
}
in.close();
}
}
我正在尝试从Android手机连接到该服务器。我已在我的宣言中设置了所有必需的权限 - INTERNET和ACCESS_NETWORK_STATE。这是我的AsyncTask。我已经尝试创建任务对象并在OnCreate()中调用其execute()方法,但它没有连接。我得到一个超时说我无法找到服务器,但我尝试从具有相同IP的另一台PC连接到服务器,它的工作原理。有什么想法吗?
class MyTransmitter extends AsyncTask<String, Void, List<Address>> {
private static Socket mytransmitter;
private static PrintWriter out;
private static boolean firstReport = true;
@Override
protected List<Address> doInBackground(String... params) {
System.out.println("AsyncTask is being executed");
try {
if (firstReport) {
System.out.println("About to try create a socket!");
InetAddress serverAddr = InetAddress.getByName("155.245.119.5");
mytransmitter = new Socket(serverAddr, 8888);
out = new PrintWriter(mytransmitter.getOutputStream());
out.println("TimeStamp: " + getCurrentTimeStamp() + "; GPS_latitude: " + params[0] + "; GPS_longitude: " + params[1] + "; Speed: " + params[2] + ";");
System.out.println("TimeStamp: " + getCurrentTimeStamp() + "; GPS_latitude: " + params[0] + "; GPS_longitude: " + params[1] + "; Speed: " + params[2] + ";");
out.flush();
firstReport = false;
}
else {
out.println("TimeStamp: " + getCurrentTimeStamp() + "; GPS_latitude: " + params[0] + "; GPS_longitude: " + params[1] + "; Speed: " + params[2] + ";");
System.out.println("TimeStamp: " + getCurrentTimeStamp() + "; GPS_latitude: " + params[0] + "; GPS_longitude: " + params[1] + "; Speed: " + params[2] + ";");
out.flush();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}