用socket簡單實現C/S聊天通信

主想想法:在客戶端上發送一條信息,在後臺開辟一個線程充當服務端,收到消息就立即回饋給客戶端。

第一步:創建一個繼續Activity的SocketClientActity類,包為com.pku.net

編寫佈局文件socketclient.xml,代碼如下:

 

[html] <?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="發送" > 
    </Button> 
 
</LinearLayout> 
<?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="發送" >
    </Button>

</LinearLayout>

 

 

接下來編寫SocketClientActity.java文件:

 

[java] 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; 
    } 

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;
 }
}

 

 

編寫AndroidManifest.xml文件:

 

[html] <?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> 
<?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>

 

 

最後編寫後臺服務端的文件SocketServerThread.java,代碼如下:

 

[java] 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(); 
        // 創建Socket服務器  
    } 
 
    public void run() { 
        Socket client; 
        String txt; 
        try { 
            while (true) 
            // 線程無限循環,實時監聽socket端口  
            { 
                client = ResponseSocket(); 
                // 響應客戶端鏈接請求。。  
 
                while (true) { 
                    txt = ReceiveMsg(client); 
                    System.out.println(txt); 
                    // 鏈接獲得客戶端發來消息,並將其顯示在Server端的屏幕上  
 
                    SendMsg(client, txt); 
                    // 向客戶端返回消息  
                    if (true) 
                        break; 
                    // 中斷,繼續等待鏈接請求  
                } 
 
                CloseSocket(client); 
                // 關閉此次鏈接  
            } 
        } 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("Server starting.."); 
    } 
 
    private Socket ResponseSocket() throws IOException { 
        Socket client = server.accept(); 
        System.out.println("client connected.."); 
 
        return client; 
    } 
 
    private void CloseSocket(Socket socket) throws IOException { 
        reader.close(); 
        writer.close(); 
        socket.close(); 
        System.out.println("client closed.."); 
    } 
 
    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("server get input from client socket.."); 
        String txt = "Sever send:" + reader.readLine(); 
 
        return txt; 
    } 
 /*
    public static void main(final String args[]) throws IOException {
        SocketServerThread yaochatserver = new SocketServerThread();
        if (yaochatserver != null) {
            yaochatserver.start();
        }
    }   */ 
 

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();
  // 創建Socket服務器
 }

 public void run() {
  Socket client;
  String txt;
  try {
   while (true)
   // 線程無限循環,實時監聽socket端口
   {
    client = ResponseSocket();
    // 響應客戶端鏈接請求。。

    while (true) {
     txt = ReceiveMsg(client);
     System.out.println(txt);
     // 鏈接獲得客戶端發來消息,並將其顯示在Server端的屏幕上

     SendMsg(client, txt);
     // 向客戶端返回消息
     if (true)
      break;
     // 中斷,繼續等待鏈接請求
    }

    CloseSocket(client);
    // 關閉此次鏈接
   }
  } 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("Server starting..");
 }

 private Socket ResponseSocket() throws IOException {
  Socket client = server.accept();
  System.out.println("client connected..");

  return client;
 }

 private void CloseSocket(Socket socket) throws IOException {
  reader.close();
  writer.close();
  socket.close();
  System.out.println("client closed..");
 }

 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("server get input from client socket..");
  String txt = "Sever send:" + reader.readLine();

  return txt;
 }
 /*
 public static void main(final String args[]) throws IOException {
  SocketServerThread yaochatserver = new SocketServerThread();
  if (yaochatserver != null) {
   yaochatserver.start();
  }
 }   */

}

 

 

運行效果如下圖:

摘自 北京大學-Google Android實驗室

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。