Android Socket编程简单的网络聊天程序.docx

上传人:b****3 文档编号:10903519 上传时间:2023-05-28 格式:DOCX 页数:18 大小:123.06KB
下载 相关 举报
Android Socket编程简单的网络聊天程序.docx_第1页
第1页 / 共18页
Android Socket编程简单的网络聊天程序.docx_第2页
第2页 / 共18页
Android Socket编程简单的网络聊天程序.docx_第3页
第3页 / 共18页
Android Socket编程简单的网络聊天程序.docx_第4页
第4页 / 共18页
Android Socket编程简单的网络聊天程序.docx_第5页
第5页 / 共18页
Android Socket编程简单的网络聊天程序.docx_第6页
第6页 / 共18页
Android Socket编程简单的网络聊天程序.docx_第7页
第7页 / 共18页
Android Socket编程简单的网络聊天程序.docx_第8页
第8页 / 共18页
Android Socket编程简单的网络聊天程序.docx_第9页
第9页 / 共18页
Android Socket编程简单的网络聊天程序.docx_第10页
第10页 / 共18页
Android Socket编程简单的网络聊天程序.docx_第11页
第11页 / 共18页
Android Socket编程简单的网络聊天程序.docx_第12页
第12页 / 共18页
Android Socket编程简单的网络聊天程序.docx_第13页
第13页 / 共18页
Android Socket编程简单的网络聊天程序.docx_第14页
第14页 / 共18页
Android Socket编程简单的网络聊天程序.docx_第15页
第15页 / 共18页
Android Socket编程简单的网络聊天程序.docx_第16页
第16页 / 共18页
Android Socket编程简单的网络聊天程序.docx_第17页
第17页 / 共18页
Android Socket编程简单的网络聊天程序.docx_第18页
第18页 / 共18页
亲,该文档总共18页,全部预览完了,如果喜欢就下载吧!
下载资源
资源描述

Android Socket编程简单的网络聊天程序.docx

《Android Socket编程简单的网络聊天程序.docx》由会员分享,可在线阅读,更多相关《Android Socket编程简单的网络聊天程序.docx(18页珍藏版)》请在冰点文库上搜索。

Android Socket编程简单的网络聊天程序.docx

AndroidSocket编程简单的网络聊天程序

1、实验名称:

AndroidSocket编程

(1)

简单的网络聊天程序

二、实验日期:

2014-09-16/2014-09-17

三、实验目的(实验题目):

1.使用Java语言编写一个简单的服务器,使用Java集合保存与服务器连接的多个客户端的Socket,当有客户端向服务器发送消息是,遍历该集合中的所有Socket对象,并向所有链接到服务器的客户端转发消息。

使用线程池技术处理客户消息。

2.编写一个Android客户端,用来实现与1.题的服务器进行通信,能够发送、接收聊天消息。

由于Android4.0以上的SDK要求不能再UI线程里做I/O、Socket连接等操作,需要进行特殊处理(处理方法见大课课件)。

分别采用2中方法处理Socket连接、I/O等操作。

使用Handler发送消息访问主线程里的UI组件。

参考界面:

参考布局XML文件:

xmlversion="1.0"encoding="utf-8"?

>

android="

android:

orientation="vertical"android:

layout_width="fill_parent"

android:

layout_height="fill_parent">

id="@+id/login"

android:

layout_width="wrap_content"

android:

layout_height="wrap_content"

android:

text="登陆"/>

id="@+id/record"

android:

layout_width="fill_parent"

android:

layout_height="wrap_content"/>

id="@+id/content"

android:

layout_width="fill_parent"

android:

layout_height="wrap_content"/>

android:

text="你好:

"

android:

orientation="horizontal"

android:

layout_width="fill_parent"

android:

layout_height="wrap_content">

id="@+id/send"

android:

layout_width="90dip"

android:

layout_height="wrap_content"

android:

text="发送"/>

id="@+id/clear"

android:

layout_width="140dip"

android:

layout_height="wrap_content"

android:

text="清空聊天记录"/>

id="@+id/author"

android:

layout_width="90dip"

android:

layout_height="wrap_content"

android:

text="签名"/>

附:

Socket连接的关键代码

(1)服务器端关键代码:

1)//建立Socket服务

ServerSocketserver=newServerSocket(18888);

2)//接收请求

socket=server.accept();

3)//接收客户端消息

BufferedReaderin=newBufferedReader(newInputStreamReader(socket.getInputStream()));

Stringmessage=in.readLine();

4)//发送消息,向客户端

PrintWriterout=newPrintWriter(newBufferedWriter(newOutputStreamWriter(socket.getOutputStream())),true);

out.println("Server:

"+message);

5)//关闭流

in.close();

out.close();

(2)Android客户端关键代码:

Socketsocket=null;

Stringmessage=editText.getText().toString()+"\r\n";

socket=newSocket("10.0.2.2",18888);

PrintWriterout=

newPrintWriter(newBufferedWriter(newOutputStreamWriter(socket.getOutputStream())),true);

//发送数据

out.println(message);

//接收数据

BufferedReaderin=newBufferedReader(newInputStreamReader(socket.getInputStream()));

Stringmsg=in.readLine();

editText.setText(msg);

//关闭流

out.close();

in.close();

四、实验用的仪器和材料:

1.PC机;

2.Widows操作系统

3.AdroidSDK,ADT,Eclipse开发环境

4.Network

5.Androidmobile

五、实验的步骤和方法(程序代码及、注释、说明):

1.

服务器端代码:

package;

importjava.io.BufferedReader;

importjava.io.IOException;

importjava.io.InputStreamReader;

importjava.io.PrintWriter;

import.ServerSocket;

import.Socket;

importjava.util.ArrayList;

importjava.util.List;

importjava.util.concurrent.ExecutorService;

importjava.util.concurrent.Executors;

/**

*Android简易聊天室(服务器端)

*

*@infoMyEclipse右键运行

*@info命令行cd到文件路径(如:

E:

\Android\client2_13\bin\),执行java.Server

*@authormao2012-6-20上午10:

40:

19

*/

publicclassServer{

/*端口5000*/

privatestaticfinalintSERVERPORT=5000;

/*所有已连接的客户端*/

privatestaticListclientList=newArrayList();

/**线程缓存池*/

privateExecutorServiceexecutorService;

/**服务器套接字*/

privateServerSocketserverSocket;

/**main函数*/

publicstaticvoidmain(String[]args){

newServer();

}

publicServer(){

try{

serverSocket=newServerSocket(SERVERPORT);

executorService=Executors.newCachedThreadPool();

System.out.println("服务器已启动...");

Socketclient=null;

while(true){

//等待客户消息

client=serverSocket.accept();

//保存每次的客户套接字

clientList.add(client);

//启动一个线程去处理客户消息

executorService.execute(newThreadServer(client));

}

}catch(IOExceptione){

System.out.println("套接字异常!

");

e.printStackTrace();

}

}

/**消息处理线程*/

staticclassThreadServerimplementsRunnable{

privateSocketsocket;

privateBufferedReaderbr;

privatePrintWriterpw;

privateStringmsg;

publicThreadServer(Socketsocket)throwsIOException{

this.socket=socket;

//初始化输入流,采用UTF-8字符集

br=newBufferedReader(newInputStreamReader(

socket.getInputStream(),"UTF-8"));

msg="用户:

"+this.socket.getInetAddress()+"来啦~请求次数:

"

+clientList.size();

sendMessage();

}

/*线程运行方法*/

publicvoidrun(){

try{

while((msg=br.readLine())!

=null){

if(msg.trim().equals("exit")){//退出

clientList.remove(socket);

br.close();

pw.close();

msg="用户:

"+this.socket.getInetAddress()

+"退出.请求次数:

"+clientList.size();

socket.close();

sendMessage();

break;

}elseif(msg.trim().equals("clear")){//清空聊天记录

msg=socket.getInetAddress()+":

";

sendMessage();

}elseif(!

"".equals(msg.trim())){//普通聊天消息

msg=socket.getInetAddress()+":

"+msg;

sendMessage();

}

}

}catch(IOExceptione){

e.printStackTrace();

}

}

/**向客户端回送消息*/

privatevoidsendMessage()throwsIOException{

System.out.println(msg);

for(Socketclient:

clientList){

pw=newPrintWriter(client.getOutputStream(),true);

pw.println(msg);

}

}

}

}

 

2.

Android客户端;

布局文件

xmlversion="1.0"encoding="utf-8"?

>

android="

android:

layout_width="fill_parent"

android:

layout_height="fill_parent"

android:

orientation="vertical">

android:

id="@+id/login"

android:

layout_width="wrap_content"

android:

layout_height="wrap_content"

android:

text="登陆"/>

android:

id="@+id/record"

android:

layout_width="fill_parent"

android:

layout_height="wrap_content"/>

android:

id="@+id/content"

android:

layout_width="fill_parent"

android:

layout_height="wrap_content"/>

android:

layout_width="fill_parent"

android:

layout_height="wrap_content"

android:

orientation="horizontal">

android:

id="@+id/send"

android:

layout_width="90dip"

android:

layout_height="wrap_content"

android:

text="发送"/>

android:

id="@+id/clear"

android:

layout_width="140dip"

android:

layout_height="wrap_content"

android:

text="清空聊天记录"/>

android:

id="@+id/author"

android:

layout_width="90dip"

android:

layout_height="wrap_content"

android:

text="签名"/>

代码:

packagecom.example.week03_1;

importjava.io.BufferedReader;

importjava.io.InputStreamReader;

importjava.io.PrintWriter;

import.Socket;

importandroid.annotation.TargetApi;

importandroid.app.Activity;

importandroid.os.Build;

importandroid.os.Bundle;

importandroid.os.Handler;

importandroid.os.Message;

importandroid.os.StrictMode;

importandroid.util.Log;

importandroid.view.View;

importandroid.view.View.OnClickListener;

importandroid.widget.Button;

importandroid.widget.EditText;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)

publicclassClientActivityextendsActivity{

privatefinalStringDEBUG_TAG="Client";

/**

*123.82.50.70127.0.0.110.0.2.2这个代表模拟器所在电脑的IP10.0.2.15

*/

privatestaticfinalStringSERVERIP="172.16.28.67";

privatestaticfinalintSERVERPORT=5000;

privateThreadthread=null;

privateSocketsocket=null;

privateButtonlogin=null;

privateButtonsend=null;

privateEditTextrecord=null;

privateEditTextcontent=null;

privateButtonclear=null;

privateButtonauthor=null;

privateBufferedReaderbr=null;

privatePrintWriterpw=null;

privateStringstrMsg="";

privatestaticfinalStringAUTHOR="小懒猫~";

publicvoidonCreate(BundlesavedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_client);

login=(Button)findViewById(R.id.login);

send=(Button)findViewById(R.id.send);

clear=(Button)findViewById(R.id.clear);

author=(Button)findViewById(R.id.author);

record=(EditText)findViewById(R.id.record);

content=(EditText)findViewById(R.id.content);

//android4.0UI

StrictMode.setThreadPolicy(newStrictMode.ThreadPolicy.Builder()

.detectDiskReads().detectDiskWrites().detectNetwork()

.penaltyLog().build());

StrictMode.setVmPolicy(newStrictMode.VmPolicy.Builder()

.detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath()

.build());

//登陆

login.setOnClickListener(newOnClickListener(){

publicvoidonClick(Viewv){

try{

socket=newSocket(SERVERIP,SERVERPORT);

//初始化输入流,采用UTF-8字符集

br=newBufferedReader(newInputStreamReader(socket

.getInputStream(),"gb2312"));

pw=newPrintWriter(socket.getOutputStream(),true);

}catch(Exceptione){

Log.e(DEBUG_TAG,"登陆失败!

"+e.toString());

}

}

});

//发送

send.setOnClickListener(newOnClickListener(){

publicvoidonClick(Viewv){

try{

Stringstr=content.getText().toString()+"\n";

pw.println(str);

pw.flush();

}catch(Exceptione){

Log.e(DEBUG_TAG,"发送失败!

"+e.toString());

}

}

});

//清除聊天记录

clear.setOnClickListener(newOnClickListener(){

publicvoidonClick(Viewv){

try{

strMsg="";

pw.println("clear");

pw.flush();

}catch(Exceptione){

Log.e(DEBUG_TAG,"发送失败!

"+e.toString());

}

}

});

//签名

author.setOnClickListener(newOnClickListener(){

publicvoidonClick(Viewv){

try{

pw.println(AUTHOR);

pw.flush();

}catch(Exceptione){

Log.e(DEBUG_TAG,"发送失败!

"+e.toString());

}

}

});

//启动用于监听服务器消息的线程

thread=newThread(runnable);

thread.start();

}

展开阅读全文
相关资源
猜你喜欢
相关搜索
资源标签

当前位置:首页 > 表格模板 > 合同协议

copyright@ 2008-2023 冰点文库 网站版权所有

经营许可证编号:鄂ICP备19020893号-2