Android基于socket實(shí)現(xiàn)的簡(jiǎn)單C/S聊天通信功能
本文實(shí)例講述了Android基于socket實(shí)現(xiàn)的簡(jiǎn)單C/S聊天通信功能。分享給大家供大家參考,具體如下:
主要想法:在客戶端上發(fā)送一條信息,在后臺(tái)開辟一個(gè)線程充當(dāng)服務(wù)端,收到消息就立即回饋給客戶端。
第一步:創(chuàng)建一個(gè)繼續(xù)Activity的SocketClientActity類,包為com.pku.net
編寫布局文件socketclient.xml,代碼如下:
<?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="發(fā)送" >
</Button>
</LinearLayout>
接下來編寫SocketClientActity.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;
}
}
編寫AndroidManifest.xml文件:
<?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>
最后編寫后臺(tái)服務(wù)端的文件SocketServerThread.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();
// 創(chuàng)建Socket服務(wù)器
}
public void run() {
Socket client;
String txt;
try {
while (true)
// 線程無限循環(huán),實(shí)時(shí)監(jiān)聽socket端口
{
client = ResponseSocket();
// 響應(yīng)客戶端鏈接請(qǐng)求。。
while (true) {
txt = ReceiveMsg(client);
System.out.println(txt);
// 鏈接獲得客戶端發(fā)來消息,并將其顯示在Server端的屏幕上
SendMsg(client, txt);
// 向客戶端返回消息
if (true)
break;
// 中斷,繼續(xù)等待鏈接請(qǐng)求
}
CloseSocket(client);
// 關(guān)閉此次鏈接
}
} 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();
}
} */
}
運(yùn)行效果如下圖:

更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android通信方式總結(jié)》、《Android開發(fā)入門與進(jìn)階教程》、《Android調(diào)試技巧與常見問題解決方法匯總》、《Android多媒體操作技巧匯總(音頻,視頻,錄音等)》、《Android基本組件用法總結(jié)》、《Android視圖View技巧總結(jié)》、《Android布局layout技巧總結(jié)》及《Android控件用法總結(jié)》
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
- Android Socket實(shí)現(xiàn)多個(gè)客戶端聊天布局
- android使用Socket通信實(shí)現(xiàn)多人聊天應(yīng)用
- Android Socket通信實(shí)現(xiàn)簡(jiǎn)單聊天室
- Android使用Websocket實(shí)現(xiàn)聊天室
- 基于Socket.IO實(shí)現(xiàn)Android聊天功能代碼示例
- android Socket實(shí)現(xiàn)簡(jiǎn)單聊天小程序
- android socket聊天室功能實(shí)現(xiàn)
- android Socket實(shí)現(xiàn)簡(jiǎn)單聊天功能以及文件傳輸
- Android 基于Socket的聊天室實(shí)例
- Android Socket實(shí)現(xiàn)多個(gè)客戶端即時(shí)通信聊天
相關(guān)文章
Android實(shí)現(xiàn)點(diǎn)擊圖片上傳SQLite數(shù)據(jù)庫
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)點(diǎn)擊圖片上傳SQLite數(shù)據(jù)庫,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-08-08
android listview 水平滾動(dòng)和垂直滾動(dòng)的小例子
android listview 水平滾動(dòng)和垂直滾動(dòng)的小例子,需要的朋友可以參考一下2013-05-05
Android+OpenCV4.2.0環(huán)境配置詳解(Android studio)
這篇文章主要介紹了Android+OpenCV4.2.0環(huán)境配置詳解(Android studio),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
Android ListView萬能適配器實(shí)例代碼
本文主要介紹Android ListView萬能適配器,這里整理了詳細(xì)的資料及實(shí)現(xiàn)代碼,以及實(shí)現(xiàn)效果圖,有需要的小伙伴可以參考下2016-09-09
Android Internet應(yīng)用實(shí)現(xiàn)獲取天氣預(yù)報(bào)的示例代碼
這篇文章主要介紹了Android網(wǎng)絡(luò)編程及Internet應(yīng)用-獲取天氣,小編覺得挺不錯(cuò)的,一起跟隨小編過來看看吧2018-05-05
Android實(shí)現(xiàn)圓線按鈕進(jìn)度效果
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)圓線按鈕帶進(jìn)度,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-05-05
Android實(shí)現(xiàn)日期時(shí)間選擇對(duì)話框
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)日期以及時(shí)間選擇對(duì)話框,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
Android點(diǎn)擊事件之多點(diǎn)觸摸與手勢(shì)識(shí)別的實(shí)現(xiàn)
這篇文章主要介紹了Android點(diǎn)擊事件之多點(diǎn)觸摸與手勢(shì)識(shí)別的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05

