Android Socket and server communication common Demo, androiddemo

Source: Internet
Author: User

Android Socket and server communication common Demo, androiddemo

In Android, using Socket to connect to the server is a simple network connection method. Although it is not used much now, it is very convenient in some cases. Here we will summarize the basic writing method.

Client:

try {Socket socket = new Socket(host, port);socket.setSoTimeout(6 * 1000);PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);printWriter.println("socket test");printWriter.flush();BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));revMsg = reader.readLine();if (TextUtils.isEmpty(revMsg)) {revMsg = "Server Error";}printWriter.close();reader.close();socket.close();return revMsg;} catch (Exception e) {e.printStackTrace();revMsg = "Server Error";}

Server:

import java.net.ServerSocket;import java.net.Socket;public class Server {public static void main(String[] args) {try {ServerSocket serverSocket = new ServerSocket(8888);while (true) {Socket socket = serverSocket.accept();new ServerThread(socket);}} catch (Exception e) {e.printStackTrace();}}}

import java.io.BufferedReader;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.Socket;class ServerThread extends Thread {private Socket socket;private BufferedReader bufferedReader;private PrintWriter printWriter;public ServerThread(Socket socket) throws IOException {this.socket = socket;bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));printWriter = new PrintWriter(socket.getOutputStream(), true);System.out.println("Client(" + getName() + ") connected...");start();}@Overridepublic void run() {try {String line = bufferedReader.readLine();if (!line.equals("exit")) {System.out.println("Client(" + getName() + ") say: " + line);WriteToTxt(line + "\r\n","/local/data.txt");printWriter.println("Receive Success!");}printWriter.close();bufferedReader.close();socket.close();} catch (IOException e) {}}private void WriteToTxt(String str, String path) {try {FileWriter writer = new FileWriter(path, true);writer.write(str);writer.close();} catch (IOException e) {e.printStackTrace();}}}

The server uses multiple threads to process multiple concurrent socket requests.

Demo is simple.

Above.


How to Use socket to communicate with the server in android

Private static void send (){
Try {
Socket con = new Socket (serverIp, serverPort );
InputStream in = con. getInputStream ();
OutputStream out = con. getOutputStream ();
While (true ){
Byte [] msg = message. getBytes ();
Out. write (msg, 0, msg. length );
Out. flush ();
Byte [] tmp = new byte [1, 128];
// Receives the returned message
StringBuilder str = new StringBuilder ();
Int count = 0;
While (count = in. read (tmp)> 0 ){
String s = new String (tmp, 0, count );
Str. append (s );
If (count <tmp. length) break;
}
Log. I ("socket", "reply:" + str. toString ());
}

} Catch (Exception e ){
System. out. println (e. getMessage ());
}
}
}
This is a demo I have done before.
 
Socket communication between PC server and android mobile client

Have you made a hole in the Intranet?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.