Based on the code of the network communication for socket programming that was written in the previous two weeks, the knowledge and considerations are now summarized as follows:
1. first, the class about socket programming in Android NiO :
1) Serversocketchannel class: The server socket channel is equivalent to the traditional IO serversocket, through the serversocketchannel socket () can obtain the traditional serversocket, In turn, use ServerSocket's Getchannel () to get Serversocketchannel objects The instantiation Serversocketchannel can be done directly through the static method of the Serversocketchannel open ().
2) Socketchannel class: Socket channel equivalent to traditional IO socket, through the socketchannel socket () can obtain a traditional socket, in turn using the socket Getchannel () can obtain Socketchannel object;
3) Selector Selector: The method of registering various events in NIO is primarily implemented using selector, which we can instantiate using the static method of the Selector class, open ().
4) Selectionkey class: Is a choice key, in NiO the selector and select the key is very important, Selectionkey described the more important events in NiO, such as Op_accept, Op_read, Op_write.
2. Then say the difference between non-blocking and blocking modes and the implementation of non-blocking modes :
1) Non-blocking: so-called non-blocking means that when the server listens to the client connection, if there is no customer connection, the program is still executed, will not stop here waiting for customer connection, or customer connection, the next step is to wait for the customer to send data, if not sent, the program will not stay here, but continue to execute. In turn, staying here, not continuing is blocking.
2) Non-blocking mode implementation: For the client, after getting the Socketchannel object, by calling method Configureblocking (false) to set the socket is non-blocking state. Then interact with the server in conjunction with the use of selector and Selectionkey. The code is as follows:
Socketchannel socket = new Socketchannel (ip,port);
Socket.configureblocking (FALSE);
Mselector = Selector.open ();
Socket.register (Mselector, Selectionkey.op_read | Selectionkey.op_write);
while (true) {
mselector.select (0);
Set<SelectionKey> Readkeys = Mselector.selectedkeys ();
Iterator<SelectionKey> Iterator = Readkeys.iterator ();
while (Iterator.hasnext ()) {
Selectionkey key = (Selectionkey) iterator.next ();
iterator.remove ();
if (key.isreadable ()) {...
} else if (Key.iswritable ()) { .....
}
}
}
3. Message processing mechanism-message Handler Looper
Message handler handles sending and receiving messages Looper management messages, which is a handle
Under what circumstances should messages be used? such as a sub-thread, in the course of execution to change a control value of the main thread UI, this time need to send a message to the main thread, and the use of message processing mechanism can not interfere with the main thread to perform other operations, in the main thread as long as the handler sense that it will receive the message, and then processing. The code is as follows:
In the main thread: declare a handler
Handler Mhandler = new Handler () {
@Override
public void Handlemessage (Message msg) {
Super.handlemessage (msg);
}
};
On child Threads:
public void SendMessage (String message, int) {
Message msg = Mhandler.obtainmessage (What, 1, 1, message);
Mhandler.sendmessage (msg);
}
Note that the handler in a child thread must be the handler of the main thread declaration, so that the message sent by the thread can be received by the main threads handler aware.
4. Problems encountered
1) Threading problem: In socket programming, the implementation of the server and multiple client communication to the maximum possible use of multi-threaded mechanism to achieve, when the server monitoring a client connection to open a thread dedicated to communication with the client, if the client for some reason disconnected from the server to close the thread in a timely manner Of course, if the server is disconnected, all threads that communicate with the client are closed. In Android development, it is important to note that a more time-consuming operation is best done by a single thread, or the main thread delays performing other operations because of this time-consuming operation, which results in poor program efficiency.
2) Network problems: Android Development, often encounter the server and the client is communicating when suddenly the network is broken, this time to close the socket, but when the socket is closed, both sides to know that the network is broken to shut down, if it is artificially closed socket, the other party will certainly be able to detect, However, the network suddenly disconnected, it can not be detected, the solution is that the two sides connected, each time a protection packet sent, the two sides to send, receive not processing, if in a period of time, the party neither send normal packets nor send protection packets, Then close the socket, which solves the problem that the network disconnection caused one party not to close the socket in time.
3) Socket shutdown problem: In the socket programming, encountered an exception or other need to disconnect the case, the socket should be closed in time, and before closing the socket, to ensure that the thread closed; For example, the client is disconnected from the server, At this point the server detects that the channel with this client has been shut down and an exception occurs when the server shuts down the thread and socket.
There is also a particularly important issue in Android development, if the server communicates with the client, if there is no protocol defined, simply send a string, then if one party sends a null value, this time the other party will default that you do not send the data. The solution to this problem is to either define a canonical protocol to send the data, that is, each send a data has a header, or define a specialized packet (such as 1 of byte type) to represent a null value.
--------------------------------------------------------------------------------------------------------------- ------------------------------------------------------
Get the phone IP address
The first type:
public int getipaddress () {
Wifimanager Wifimanager = (wifimanager) this.context
. Getsystemservice (Context.wifi_service);
Determine if WiFi is turned on
if (!wifimanager.iswifienabled ()) {
Wifimanager.setwifienabled (TRUE);
}
Wifiinfo wifiinfo = Wifimanager.getconnectioninfo ();
int ipAddress = wifiinfo.getipaddress ();
return ipAddress;
}
Private String Inttoip (int i) {
Return (I & 0xFF) + "." + (((I >> 8) & 0xFF) + "." + ((I >> +) & 0xFF)
+ "." + (I >> & 0xFF);
}
The second type :
Public String getinetipaddress () {
try {
for (enumeration<networkinterface> en = networkinterface
. Getnetworkinterfaces (); En.hasmoreelements ();) {
NetworkInterface intf = En.nextelement ();
for (enumeration<inetaddress> ipaddr = intf.getinetaddresses (); ipaddr
. hasMoreElements ();) {
InetAddress inetaddress = Ipaddr.nextelement ();
return inetaddress.gethostaddress ();
}
}
} catch (Exception e) {
E.printstacktrace ();
}
return null;
}
Http://www.cnblogs.com/crearo-ssy/archive/2012/08/16/2640612.html
Socket programming summary-android communication between the mobile server and multiple Android phone clients (non-blocking)