English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

A simple C implementation based on socket in Android/S chat communication function

This article describes a simple C implementation of Android based on socket:/Share the chat communication function with everyone for reference, as follows:

Main idea: Send a message on the client side, and open a thread in the background to act as the server, and immediately feedback to the client when a message is received.

Step 1: Create a SocketClientActity class that extends Activity, the package is com.pku.net

Write the layout file socketclient.xml, the code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >
  <ScrollView
    android:id="@"+id/scrollview3"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >
    <TextView
      android:id="@"+id/chattxt2"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:background="#"98F5FF" />
  </ScrollView>
  <EditText
    android:id="@"+id/chattxt"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />
  <Button
    android:id="@"+id/chatOk"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Send" >
  </Button>
</LinearLayout>

Next, write the SocketClientActity.java file:

package com.pku.net;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.UnknownHostException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class SocketClientActivity extends Activity {
  SocketServerThread yaochatserver;
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.socketclient);
    try {
      yaochatserver = new SocketServerThread();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    if (yaochatserver != null) {
      yaochatserver.start();
    }
    findviews();
    setonclick();
  }
  private EditText chattxt;
  private TextView chattxt2;
  private Button chatok;
  public void findviews() {
    chattxt = (EditText) this.findViewById(R.id.chattxt);
    chattxt2 = (TextView) this.findViewById(R.id.chattxt2);
    chatok = (Button) this.findViewById(R.id.chatOk);
  }
  private void setonclick() {
    chatok.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        try {
          connecttoserver(chattxt.getText().toString());
        } catch (UnknownHostException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    });
  }
  public void connecttoserver(String socketData) throws UnknownHostException,
      IOException {
    Socket socket = RequestSocket("127.0.0.1", 5000);
    SendMsg(socket, socketData);
    String txt = ReceiveMsg(socket);
    this.chattxt2.setText(txt);
  }
  private Socket RequestSocket(String host, int port) {}
      throws UnknownHostException, IOException {
    Socket socket = new Socket(host, port);
    return socket;
  }
  private void SendMsg(Socket socket, String msg) throws IOException {
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
        socket.getOutputStream()));
    writer.write(msg.replace("\n", " ")); + "\n");
    writer.flush();
  }
  private String ReceiveMsg(Socket socket) throws IOException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
        socket.getInputStream()));
    String txt = reader.readLine();
    return txt;
  }
}

Write an AndroidManifest.xml file:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="com.pku.net"
  android:versionCode="1"
  android:versionName="1.0">
  <uses-sdk android:minSdkVersion="8" />
  <uses-permission android:name="android.permission.INTERNET">/>
  <application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name">
    <activity
      android:name=".HttpURLActivity">
      android:label="@string/app_name">
      <intent-filter>
        <action android:name="android.intent.action.MAIN"> />
        <category android:name="android.intent.category.LAUNCHER"> />
      </intent-filter>
    </activity>
    <activity android:name="GetNetImage"></activity>
    <activity android:name="HttpClientActivity"></activity>
    <activity android:name="SocketClientActivity"></activity>
  </application>
</manifest>

Finally, write the background server file SocketServerThread.java, as follows:

package com.pku.net;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServerThread extends Thread {
  public SocketServerThread() throws IOException {
    CreateSocket();
    // Create a Socket server
  }
  public void run() {
    Socket client;
    String txt;
    try {
      while (true)
      // Thread runs in an infinite loop, listening to the socket port in real time
      {
        client = ResponseSocket();
        // Respond to the client's connection request...
        while (true) {
          txt = ReceiveMsg(client);
          System.out.println(txt);
          // The server receives a message from the client and displays it on the server's screen
          SendMsg(client, txt);
          // Send a message to the client
          if (true)
            break;
          // Interrupt and continue waiting for a connection request
        }
        CloseSocket(client);
        // Close this connection
      }
    } catch (IOException e) {
      System.out.println(e);
    }
  }
  private ServerSocket server = null;
  private static final int PORT = 5000;
  private BufferedWriter writer;
  private BufferedReader reader;
  private void CreateSocket() throws IOException {
    server = new ServerSocket(PORT, 100);
    System.out.println("服务器启动中...");
  }
  private Socket ResponseSocket() throws IOException {
    Socket client = server.accept();
    System.out.println("客户端已连接...");
    return client;
  }
  private void CloseSocket(Socket socket) throws IOException {
    reader.close();
    writer.close();
    socket.close();
    System.out.println("客户端已关闭...");
  }
  private void SendMsg(Socket socket, String Msg) throws IOException {
    writer = new BufferedWriter(new OutputStreamWriter(
        socket.getOutputStream()));
    writer.write(Msg + "\n");
    writer.flush();
  }
  private String ReceiveMsg(Socket socket) throws IOException {
    reader = new BufferedReader(new InputStreamReader(
        socket.getInputStream()));
    System.out.println("服务器从客户端套接字接收输入...");
    String txt = "服务器发送:" + reader.readLine();
    return txt;
  }
 /*
  public static void main(final String args[]) throws IOException {
    SocketServerThread yaochatserver = new SocketServerThread();
    if (yaochatserver != null) {
      yaochatserver.start();
    }
  }  */
}

The running effect is shown in the figure below:

Readers who are interested in more content related to Android can check the special topics on this site: 'Summary of Android Communication Methods', 'Introduction and Advanced Tutorial of Android Development', 'Summary of Android Debugging Techniques and Common Problem Solving Methods', 'Summary of Android Multimedia Operation Techniques (audio, video, recording, etc.)', 'Summary of Usage of Android Basic Components', 'Summary of Techniques of Android View View', 'Summary of Techniques of Android Layout layout', and 'Summary of Usage of Android Controls'.

Hoping that the content described in this article will be helpful to everyone in Android program design.

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously, and this website does not own the copyright, has not been edited by人工, nor does it assume relevant legal liabilities. If you find any content suspected of copyright infringement, please feel free to send an email to notice#w.3If you find any copyright infringement, please send an email to notice#w with the # replaced by @ and provide relevant evidence. Once verified, this site will immediately delete the suspected infringing content.

You may also like