1. Socket INTRODUCTION
2. Establishment and use of ServerSocket
3. Setting up a chat server with ServerSocket-1
4. Setting up a chat server with ServerSocket-2
5. Create a socket client in Android
------------------------------------------------------------------
1. Socket INTRODUCTION
The socket is also called a socket, and the application usually makes a request to the network through a "socket" or answers a network request. ServerSocket is used for server-side, Socket is used when establishing network connection. When the connection succeeds, a Socket instance is generated at both ends of the application, manipulating the instance to complete the required session.
For a network connection, sockets are equal, no difference, and are not applied on the server side or the client to produce different levels.
Either the socket or the ServerSocket their work is done through the socket class and its subclasses.
* Based on TCP connection, data transmission is guaranteed
* Suitable for long-time connection establishment
* Usually used for instant communication
2. Establishment and use of ServerSocket
3. Setting up a chat server with ServerSocket-1
3.1 Building the Java project: Serversocketdemo
* Chatsocket.java
Public classChatsocketextendsThread {socket socket; PublicChatsocket (socket s) {socket=s; } Public voidout (String out) {Try{socket.getoutputstream (). Write (Out.getbytes ("UTF-8")); } Catch(Exception e) {e.printstacktrace (); }} @Override Public voidrun () {intCount = 0; while(true) {Count++; Out ("Loop:" + count + ", \ T"); Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } } }}
* Serverlistener.java
Public classServerlistenerextendsThread {@Override Public voidrun () {ServerSocket serversocket; Try{ServerSocket=NewServerSocket (12345); while(true) { //listening on port 12345Socket socket =serversocket.accept (); //Establish a connectionJoptionpane.showmessagedialog (NULL, "There is a client access 12345 port"); Newchatsocket (socket). Start (); } } Catch(IOException e) {e.printstacktrace (); } }}
* Myserversocket.java
Public class myServerSocket { publicstaticvoid main (string[] args) { New Serverlistener (). Start (); }}
3.2 Administrator Privileges Open cmd window: telnet localhost 12345
Two threads complementary effects
4. Setting up a chat server with ServerSocket-2
Two client in 3 cannot communicate with each other
5. Create a socket client in Android
Create the socket client in Android. Use the socket to establish a client link, and perform network read and write tasks in Asynctask, send the user input to the server, and receive the data sent from the server, displayed to the interface. Turn on multiple virtual machines to simulate multi-person chat effects.
To create an Android project:
Socket-based network communication in Android