Android development: Tomcat server, client socket network connection problems and D-LINK port forwarding settings, androidtomcat
I used my computer to build a server. The first problem was that we needed port ing on the router to access our computer through the Internet. How to map ports can be found in this article:
Http://blog.csdn.net/zhoubin1992/article/details/45917775
1. D-LINK port forwarding settings
My ID is D-link.
Enter the name of your client.
IP Address: the IP address assigned by the router to the local machine. It generally starts with 192.168. Query Method: ipconfig in cmd
Enter a private port, which is the port to be opened by the router. You can also set a port range.
The public port is the port to be accessed from the Internet.
Select any traffic type.
Ii. socket communication program error
Run Socket socket = new Socket ("xx. xx. xxx. xxx", 8888); then an exception is thrown. A timeout error is reported.
The reason is that the client cannot connect to the socket.
Solution:
1. First, make sure to open another thread to complete the network connection.
New Thread () {public void run () {try {// connect to the network and open the stream s = new Socket ("110.83.75.12", 8888); dout = new DataOutputStream (s. getOutputStream (); din = new DataInputStream (s. getInputStream ();} catch (Exception e) {// catch Exception e. printStackTrace (); // print exception}
2. This still doesn't work. Finally, I found the answer in StackOverflow and needed to enable StrictMode in OnCreate.
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .penaltyLog() .penaltyDeath() .build()); }
I don't know why strict mode is required. If anyone knows this, leave a message to me.
Now I can communicate with each other, but when I use my own 3G traffic for access, there is another problem. Check and find that the local IP address of the socket is incorrect.
The local machine also has an Internet IP address. How to obtain it: Enter the IP address of the Local Machine on Baidu, and the real IP address of the Local Machine appears.
Then replace the IP address of Socket ("xx. xx. xxx. xxx", 8888 ~