Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Socket Communication in Android

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Editor to share with you how to achieve Socket communication in Android, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!

The company wants to achieve a simple chat function, study the Socket communication in advance, but the server function of the company has not been realized, so here the server function is implemented in an interface.

Go directly to the code:

Main code:

Package com.app.socketdemo; import android.annotation.SuppressLint;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.text.Html;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.ScrollView;import android.widget.TextView;import android.widget.Toast; import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream Import java.net.InetAddress;import java.net.ServerSocket;import java.net.Socket; import androidx.appcompat.app.AppCompatActivity;import butterknife.BindView;import butterknife.ButterKnife;import butterknife.OnClick; public class MainActivity extends AppCompatActivity {@ BindView (R.id.et_ip) EditText etIp; @ BindView (R.id.btn_connect) Button btnConnect; @ BindView (R.id.tv_receive) TextView tvReceive; @ BindView (R.id.tv_content) TextView tvContent @ BindView (R.id.et_input) EditText etInput; @ BindView (R.id.btn_send) Button btnSend; @ BindView (R.id.sv_content) ScrollView svContent; @ BindView (R.id.btn_service) Button btnService; private StringBuffer strMsg = new StringBuffer (); private final int MESSAGE_ERROR = 0; private final int MESSAGE_SUCCEED = 1; private final int MESSAGE_RECEIVE = 2; private Socket sock; private OutputStream outx Private InputStream inx; @ Override protected void onCreate (Bundle savedInstanceState) {super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); ButterKnife.bind (this); / / start server new Thread (()-> new Server () .startService ()) .start () } @ OnClick ({R.id.btn_connect, R.id.btn_service, R.id.btn_send}) public void onViewClicked (View view) {switch (view.getId ()) {case R.id.btn_connect:// connection server String strip = etIp.getText () .toString () .trim () If (strip.indexOf (":") > = 0) {/ / start the connection new Socket_thread (strip) .start ();} break Case R.id.btn_service: if (! TextUtils.isEmpty (etInput.getText (). ToString () {sendString ("server:" + etInput.getText () .toString () .trim ()); etInput.setText ("") } else {Toast.makeText (this, "input cannot be null", Toast.LENGTH_SHORT). Show ();} break Case R.id.btn_send: if (! TextUtils.isEmpty (etInput.getText (). ToString () {sendStrSocket ("client:" + etInput.getText () .toString () .trim ()); etInput.setText ("") } else {Toast.makeText (this, "input cannot be empty", Toast.LENGTH_SHORT). Show ();} break;}} / * * Connect server * / class Socket_thread extends Thread {private String IP = ""; / / ip address private int PORT = 0 / / Port number public Socket_thread (String strip) {/ / such as: 127.0.0.1 String [] stripx = strip.split (":"); this.IP = stripx [0]; this.PORT = Integer.parseInt (stripx [1]) } @ Override public void run () {try {disSocket (); / / connect to the server, which will remain blocked until the connection succeeds sock = new Socket (this.IP, this.PORT) / / blocking stops, indicating successful connection setMessage ("connection successful", MESSAGE_SUCCEED);} catch (Exception e) {setMessage ("exception while connecting to the server", MESSAGE_ERROR); e.printStackTrace (); return } try {/ / get the input / output stream outx = sock.getOutputStream (); inx = sock.getInputStream ();} catch (Exception e) {setMessage ("get input / output stream exception", MESSAGE_ERROR); e.printStackTrace (); return } new Inx (). Start ();}} / * * receive data in a loop * / class Inx extends Thread {@ Override public void run () {while (true) {byte [] bu = new byte [1024] Try {int conut = inx.read (bu); / / device restart, the exception will remain here if (conut = =-1) {setMessage ("server down", MESSAGE_ERROR); disSocket (); return } String strread = new String (bu, "GBK"). Trim (); setMessage (strread, MESSAGE_RECEIVE);} catch (IOException e) {System.out.println (e) }} / * disconnect * / private void disSocket () {if (sock! = null) {try {outx.close (); inx.close (); sock.close (); sock = null } catch (Exception e) {setMessage ("error occurred while disconnecting", MESSAGE_ERROR) @ SuppressLint ("HandlerLeak") private Handler handler = new Handler () {@ Override public void handleMessage (Message msg) {switch (msg.arg1) {case MESSAGE_ERROR: disSocket (); strMsg.append (msg.obj + "

"); tvContent.setText (Html.fromHtml (strMsg.toString (); break; case MESSAGE_SUCCEED: strMsg.append (msg.obj +"

"); tvContent.setText (Html.fromHtml (strMsg.toString (); break; case MESSAGE_RECEIVE: / / received data strMsg.append (msg.obj); if (! strMsg.toString (). Substring (strMsg.length ()-4, strMsg.length ()) .equals ("

") {strMsg.append ("

TvContent.setText (Html.fromHtml (strMsg.toString (); svContent.fullScroll (ScrollView.FOCUS_DOWN); break; default: break;} / * send message * / private void sendStrSocket (final String senddata) {new Thread (new Runnable () {@ Override public void run () {try {String str = "" + senddata + ""; outx.write (str.getBytes ("gbk") / / "utf-8"} catch (Exception e) {setMessage ("data sending exception", MESSAGE_ERROR);}) .start ();} / * message handling * / private void setMessage (String obj, int arg1) {Message message = new Message () Message.arg1 = arg1; message.obj = obj; handler.sendMessage (message) } / * server (for testing) * * * / private String msg = "" Public class Server {ServerSocket serverSocket = null; public final int port = 8081; public Server () {/ / the IP address of the output server try {InetAddress addr = InetAddress.getLocalHost (); serverSocket = new ServerSocket (port);} catch (IOException e) {e.printStackTrace () }} public void startService () {try {while (true) {Socket socket = null; socket = serverSocket.accept (); / / wait for a client connection. Before connecting, this method is blocked new ConnectThread (socket) .start () New ConnectThread1 (socket) .start ();}} catch (IOException e) {e.printStackTrace ();}} / * send a message to the client * / class ConnectThread extends Thread {Socket socket = null Public ConnectThread (Socket socket) {super (); this.socket = socket;} @ Override public void run () {try {DataOutputStream out = new DataOutputStream (socket.getOutputStream ()) While (true) {Thread.sleep (1000); if (! TextUtils.isEmpty (msg)) {String str = "" + msg + ""; out.write (str.getBytes ("gbk")); out.flush () Msg = "";} catch (IOException e) {e.printStackTrace ();} catch (InterruptedException e) {e.printStackTrace () } / * receive client information * / class ConnectThread1 extends Thread {Socket socket = null; public ConnectThread1 (Socket socket) {super (); this.socket = socket } @ Override public void run () {try {DataInputStream inp = new DataInputStream (socket.getInputStream ()); while (true) {byte [] bu = new byte [1024]; int conut = inp.read (bu) / / device restart, the exception will remain here if (conut = =-1) {setMessage ("server disconnected", MESSAGE_ERROR); return;} String strread = new String (bu, "GBK") .trim () SetMessage (strread, MESSAGE_RECEIVE);}} catch (IOException e) {e.printStackTrace ();}} private void sendString (String str) {msg = str;}}

Running effect:

These are all the contents of the article "how to achieve Socket Communication in Android". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report