- 浏览: 516246 次
- 性别:
- 来自: 北京
文章分类
最新评论
-
tangyunliang:
大哥你太历害了谢谢
Android基于XMPP Smack Openfire开发IM【四】初步实现两个客户端通信 -
u013015029:
LZ,请问下,在// 添加消息到聊天窗口 , 这里获取Ed ...
Android基于XMPP Smack Openfire开发IM【四】初步实现两个客户端通信 -
endual:
怎么保持会话,我搞不懂啊
Android基于XMPP Smack Openfire开发IM【一】登录openfire服务器 -
donala_zq:
显示:[2013-11-30 11:50:36 - Andro ...
android-----------新浪微博 -
donala_zq:
哥,运行不了啊
android-----------新浪微博
服务器代码如下:
此为java类,在Eclipse中建个工程,放进去下,右键直接run as,服务器便已经启动。
客户端代码:
直接用模拟器运行就可以。
main.xml布局文件:
AndroidManifest.xml:
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { private static final int PORT = 9999; private List<Socket> mList = new ArrayList<Socket>(); private ServerSocket server = null; private ExecutorService mExecutorService = null; //thread pool public static void main(String[] args) { new Main(); } public Main() { try { server = new ServerSocket(PORT); mExecutorService = Executors.newCachedThreadPool(); //create a thread pool System.out.println("服务器已启动..."); Socket client = null; while(true) { client = server.accept(); //把客户端放入客户端集合中 mList.add(client); mExecutorService.execute(new Service(client)); //start a new thread to handle the connection } }catch (Exception e) { e.printStackTrace(); } } class Service implements Runnable { private Socket socket; private BufferedReader in = null; private String msg = ""; public Service(Socket socket) { this.socket = socket; try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); //客户端只要一连到服务器,便向客户端发送下面的信息。 msg = "服务器地址:" +this.socket.getInetAddress() + "come toal:" +mList.size()+"(服务器发送)"; this.sendmsg(); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { try { while(true) { if((msg = in.readLine())!= null) { //当客户端发送的信息为:exit时,关闭连接 if(msg.equals("exit")) { System.out.println("ssssssss"); mList.remove(socket); in.close(); msg = "user:" + socket.getInetAddress() + "exit total:" + mList.size(); socket.close(); this.sendmsg(); break; //接收客户端发过来的信息msg,然后发送给客户端。 } else { msg = socket.getInetAddress() + ":" + msg+"(服务器发送)"; this.sendmsg(); } } } } catch (Exception e) { e.printStackTrace(); } } /** * 循环遍历客户端集合,给每个客户端都发送信息。 */ public void sendmsg() { System.out.println(msg); int num =mList.size(); for (int index = 0; index < num; index ++) { Socket mSocket = mList.get(index); PrintWriter pout = null; try { pout = new PrintWriter(new BufferedWriter( new OutputStreamWriter(mSocket.getOutputStream())),true); pout.println(msg); }catch (IOException e) { e.printStackTrace(); } } } } }
此为java类,在Eclipse中建个工程,放进去下,右键直接run as,服务器便已经启动。
客户端代码:
package com.amaker.socket; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; /** * 除了isClose方法,Socket类还有一个isConnected方法来判断Socket对象是否连接成功。 * 看到这个名字,也许读者会产生误解。 * 其实isConnected方法所判断的并不是Socket对象的当前连接状态, * 而是Socket对象是否曾经连接成功过,如果成功连接过,即使现在isClose返回true, * isConnected仍然返回true。因此,要判断当前的Socket对象是否处于连接状态, * 必须同时使用isClose和isConnected方法, * 即只有当isClose返回false,isConnected返回true的时候Socket对象才处于连接状态。 * 虽然在大多数的时候可以直接使用Socket类或输入输出流的close方法关闭网络连接, * 但有时我们只希望关闭OutputStream或InputStream,而在关闭输入输出流的同时,并不关闭网络连接。 * 这就需要用到Socket类的另外两个方法:shutdownInput和shutdownOutput, * 这两个方法只关闭相应的输入、输出流,而它们并没有同时关闭网络连接的功能。 * 和isClosed、isConnected方法一样, * Socket类也提供了两个方法来判断Socket对象的输入、输出流是否被关闭, * 这两个方法是isInputShutdown()和isOutputShutdown()。 * shutdownInput和shutdownOutput并不影响Socket对象的状态。 */ //==================================================================================== /** * 运行过程剖析: * 1,服务器启动 * 2,客户端与服务器连接成功 * 3,服务器发送信息给客户端 的线程 * 4,线程通过Handler发送信息给UI线程 * 5,用TextView把信息显示 * * 当点击按钮时流程为: * 1,发送消息给服务器 * 2,服务器受到客户端发送来的信息,并给服务器返回信息 * 如上。 */ public class SocketDemo extends Activity implements Runnable { private TextView tv_msg = null; private EditText ed_msg = null; private Button btn_send = null; // private Button btn_login = null; private static final String HOST = "10.0.2.2"; private static final int PORT = 9999; private Socket socket = null; private BufferedReader in = null; private PrintWriter out = null; private String content = ""; //接收线程发送过来信息,并用TextView显示 public Handler mHandler = new Handler() { public void handleMessage(Message msg) { super.handleMessage(msg); tv_msg.setText(content); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv_msg = (TextView) findViewById(R.id.TextView); ed_msg = (EditText) findViewById(R.id.EditText01); btn_send = (Button) findViewById(R.id.Button02); try { socket = new Socket(HOST, PORT); in = new BufferedReader(new InputStreamReader(socket .getInputStream())); out = new PrintWriter(new BufferedWriter(new OutputStreamWriter( socket.getOutputStream())), true); } catch (IOException ex) { ex.printStackTrace(); ShowDialog("login exception" + ex.getMessage()); } btn_send.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub String msg = ed_msg.getText().toString(); if (socket.isConnected()) { if (!socket.isOutputShutdown()) { out.println(msg); } } } }); //启动线程,接收服务器发送过来的数据 new Thread(SocketDemo.this).start(); } /** * 如果连接出现异常,弹出AlertDialog! */ public void ShowDialog(String msg) { new AlertDialog.Builder(this).setTitle("notification").setMessage(msg) .setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); } /** * 读取服务器发来的信息,并通过Handler发给UI线程 */ public void run() { try { while (true) { if (!socket.isClosed()) { if (socket.isConnected()) { if (!socket.isInputShutdown()) { if ((content = in.readLine()) != null) { content += "\n"; mHandler.sendMessage(mHandler.obtainMessage()); } else { } } } } } } catch (Exception e) { e.printStackTrace(); } } }
直接用模拟器运行就可以。
main.xml布局文件:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/TextView" android:singleLine="false" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <EditText android:hint="content" android:id="@+id/EditText01" android:layout_width="fill_parent" android:layout_height="wrap_content"> </EditText> <Button android:text="send" android:id="@+id/Button02" android:layout_width="fill_parent" android:layout_height="wrap_content"> </Button> </LinearLayout>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.amaker.socket" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="10" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".SocketDemo" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <!-- 记得添加访问网络权限 --> <uses-permission android:name="android.permission.INTERNET"></uses-permission> </manifest>
发表评论
-
Android中如何模拟一次点击(touch)事件
2014-05-06 10:41 0在Android中有时需要模拟某一个View的touch事件, ... -
Android程序Crash时的异常上报
2014-04-28 18:15 0http://blog.csdn.net/singwhatiw ... -
android程序中证书签名校验的方法
2014-04-28 17:58 1897android程序中证书签名校验的方法一 2013-02 ... -
MD5理解错了,哎
2014-03-17 14:14 0MD5只对数据加密是无法解密的,也就是说,你把100加密后,就 ... -
Android 获取网络时间
2014-03-12 11:42 2006Android 获取网络时间 在网上看到的最常见的方式有: ... -
SQLite清空表并将自增列归零
2014-03-05 18:02 1461SQLite清空表并将自增列归零 作者:Zhu Yanfeng ... -
Handler小看一下
2013-11-11 16:42 0android handler调用post方法还是阻塞 su ... -
Frame Animation小看一下
2013-10-12 16:30 713Demo运行效果图: 源码: -
动画小学一下
2013-10-12 16:14 688转自: http://www.eoeandroid.com/f ... -
Android 动画之ScaleAnimation应用详解
2013-10-12 15:49 955===============eoeAndroid社区推荐:= ... -
android开发中的一个工具类
2013-06-19 16:04 0package com.wanpu.login.dialog; ... -
android TextView怎么设置个别字体颜色并换行?
2013-06-20 09:25 1629(1)、TextView 设置个别字体颜色 TextView ... -
Android开发之文件下载,状态时显示下载进度,点击自动安装
2013-05-07 15:38 1361在进行软件升级时,需要进行文件下载,在这里实现自定义的文件下载 ... -
android中的状态保存
2013-04-07 14:21 929package com.zzl.call; import ... -
android动画基础:tween动画
2013-04-06 11:21 1178工程结构图: [img] [/img] 四个动画的xml ... -
面试中遇到的几个问题
2013-06-09 11:56 936SAX与DOM之间的区别 SAX ( ... -
Android获取其他包的Context实例,然后调用它的方法,反射!!!
2013-03-25 10:32 1155Android中有Context的概念,想必大家都知道。Con ... -
Android的内存机制和常见泄漏情形
2013-03-06 16:55 750一、 Android的内存机制 Android的程序由Ja ... -
JUnit测试小小demo
2013-03-06 16:37 1080运行效果图: [img] [/img] 项目结构图 ... -
android开发中的异常小工具
2013-03-04 15:53 859package com.zzl.tools; impor ...
相关推荐
本demo是做一个Android利用蓝牙协议进行连接到心电检测设备,并且在应用上显示检测到的心电的值,用波形图,折线图显示,用到的技术点是 蓝牙协议,socket,硬件是嵌入式开发。
Netty是基于Java NIO client-server的网络应用框架,使用Netty可以快速开发网络应用
本Demo适用于博客:http://www.cnblogs.com/scetopcsa/p/4002835.html的《Android之Http网络编程(一)》、《Android之Http网络编程(二)》。就是简单的网络请求和访问,适合入门。
此demo包括两个moudle,一个Server,另一个Client,Server是个纯java文件,可以放到随便什么地方去执行,只要有JDK;Client是Android App。运行时注意修改IP为自己的IP
该文档是一个在android下写的一个socket编程的demo,希望大家有用,和大家分享!
Android socket 网络编程示例程序之1 使用了InetAddress类 本人自己编写,欢迎参考 looking for a jump
Android socket 网络编程示例程序之2 Android客户端程序与服务器端程序通信, 本人自己编写,欢迎参考 ps:looking for a jump,5000+
本文实例讲述了Android编程之客户端通过socket与服务器通信的方法。分享给大家供大家参考,具体如下: 下面是一个demo,Android客户端通过socket与服务器通信。 由于Android里面可以完全使用java.io.*包和java.net.*...
前几年的Android应用源码Demo,主要面向的是学生毕业设计学习。
用于博文https://blog.csdn.net/lyz_zyx/article/details/104062815《Android网络编程(十四) 之 Socket与NIO》中演示Socket与NIO使用的Demo
Android socket tcp应用,包含服务器和客户端,代码正常通过测试,学习使用,配合我的博客:http://blog.csdn.net/shankezh/article/details/51555455
android长连接编程 长连接实现方式 Socket设置 网络编程设计
Android应用源码安卓源码包wifi蓝牙串口&Socket通讯窗口抖动Widget小组件等20个合集: android Widget小组件开发.zip Android 开启指定名称和密码的 Wifi热点 demo.zip Android中禁止某软件的安装.zip Android小部件...
android网络通信之socket教程实例汇总 AsyncTask进度条加载网站数据到ListView 命令行开发、编译、打包Android应用程序汇总大全 Android 动画效果二 Frame Animation 动画专题研究 Android新浪客户端开发教程(完整...
(里面没有Demo,所以我就跟着教程写Demo以供学习使用) 3.目前该Demo的进度为-引导界面+人人网授权+滑动界面(左侧面板与FreshNews)+Https获取用户基本信息以及新鲜事信息+新鲜事面板的基本信息展示(图文展示)+新鲜事...
本文实例讲述了Android基于TCP和URL协议的网络编程。分享给大家供大家参考,具体如下: 手机本身是作为手机终端使用的,因此它的计算能力,存储能力都是有限的。它的主要优势是携带方便,可以随时打开,而且手机通常...
蓝牙模块服务多种多样,这个小demo实现了linux下建立蓝牙服务端的demo,并带了一个客户端测试。 使用时,可通过两台设备,分别作为服务端可客户端,连接时填入对方地址即可开启测试。服务端建立后,客户端可通过...