Android Socket通信编程
安卓客户端通过socket与服务器端通讯一般可以按照以下几个步骤:
(1).通过IP地址和端口实例化Socket,请求连接服务器:
socket = new Socket(HOST, PORT); //host:为服务器的IP地址 port:为服务器的端口号
(2).获取Socket流以进行读写,并把流包装进BufferWriter或者PrintWriter:
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
这里涉及了三个类:socket.getOutputStream得到socket的输出字节流,OutputStreamWriter是字节流向字符流转换的桥梁,BufferWriter是字符流,然后再包装进PrintWriter。
(3)对Socket进行读写
if (socket.isConnected()) {
if (!socket.isOutputShutdown()) {
out.println(msg);
}
}
(4)关闭打开的流,一定要注意对socket输入流/输出流的关闭.
out.close();
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/Button01" android:layout_width="fill_parent" android:layout_height="wrap_content"> </Button> </LinearLayout>
安卓客户端的源代码:
public class SocketDemo extends Activity implements Runnable {
private TextView tv_msg = null;
private EditText ed_msg = null;
private Button btn_send = null;
private static final String HOST = "192.168.1.150";
private static final int PORT = 9999;
private Socket socket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private String 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.Button01);
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();
}
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) {
// TODO Auto-generated method stub
}
}).show();
}
public void run() {
try {
while (true) {
if (socket.isConnected()) {
if (!socket.isInputShutdown()) {
if ((content = in.readLine()) != null) {
content += "\n";
mHandler.sendMessage(mHandler.obtainMessage());
} else {
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
tv_msg.setText(tv_msg.getText().toString() + content);
}
};
}
服务器端得java代码:
public class Main {
private static final int PORT = 9999;
private List<Socket> mList = new ArrayList<Socket>();
private ServerSocket server = null;
private ExecutorService mExecutorService = null; //线程池
public static void main(String[] args) {
new Main();
}
public Main() {
try {
server = new ServerSocket(PORT);
mExecutorService = Executors.newCachedThreadPool(); //创建一个线程池
System.out.print("server start ...");
Socket client = null;
while(true) {
client = server.accept();
mList.add(client);
mExecutorService.execute(new Service(client)); //启动一个新线程来处理连接
}
}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 = "user" +this.socket.getInetAddress() + "come toal:"
+mList.size();
this.sendmsg();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
while(true) {
if((msg = in.readLine())!= null) {
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;
} 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 i = 0; i < num; i++) {
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();
}
}
}
}
}
Android Socket通信编程的更多相关文章
- Android Socket通信详解
一.Socket通信简介 Android与服务器的通信方式主要有两种,一是Http通信,一是Socket通信.两者的最大差异在于,http连接使用的是“请求—响应方式”,即在请求时建立连接通道,当客 ...
- Android Socket 通信
Android socket 通信 安卓编写Socket客户端,实现连接Socket服务端通信. 创建Socket连接并获取服务端数据 先创建几个全局变量吧 private BufferedWrite ...
- 【转】C# Socket通信编程
https://www.cnblogs.com/dotnet261010/p/6211900.html#undefined 一:什么是SOCKET socket的英文原义是“孔”或“插座”.作为进程通 ...
- (转)android 蓝牙通信编程
转自:http://blog.csdn.net/pwei007/article/details/6015907 Android平台支持蓝牙网络协议栈,实现蓝牙设备之间数据的无线传输. 本文档描述了怎样 ...
- linux系统socket通信编程实践
简单介绍并实现了基于UDP(TCP)的windows(UNIX下流程基本一致)下的服务端和客户端的程序,本文继续探讨关于UDP编程的一些细节. 下图是一个简单的UDP客户/服务器模型: 我在这里也实现 ...
- linux系统socket通信编程详解函数
linux socket编程之TCP与UDP TCP与UDP区别 TCP---传输控制协议,提供的是面向连接.可靠的字节流服务.当客户和服务器彼此交换数据前,必须先在双方之间建立一个TCP连接,之 ...
- linux系统UDP的socket通信编程3
我刚开始接触linux下的socket编程,边抄边理解udp socket编程,我的疑问是server不指定IP地址,client的目标IP地址是127.0.0.1,这样就可以通信吗?在同一主机下是不 ...
- linux系统socket通信编程2
一.概述 TCP(传输控制协议)和UDP(用户数据报协议是网络体系结构TCP/IP模型中传输层一层中的两个不同的通信协议. TCP:传输控制协议,一种面向连接的协议,给用户进程提供可靠的全双工的字节流 ...
- linux系统socket通信编程1
Linux下的Socket编程大体上包括Tcp Socket.Udp Socket即Raw Socket这三种,其中TCP和UDP方式的Socket编程用于编写应用层的socket程序,是我们用得比较 ...
随机推荐
- 配置postfix支持虚拟域和虚拟用户
请先看基础篇 https://www.cnblogs.com/hellojackyleon/p/9281620.html https://sourceforge.net/projects/couri ...
- Mysql 乱码配置
转自: http://www.ha97.com/5359.html 一.登录MySQL查看用SHOW VARIABLES LIKE ‘character%’;下字符集,显示如下: +--------- ...
- 51nod 1273 旅行计划——思维题
某个国家有N个城市,编号0 至 N-1,他们之间用N - 1条道路连接,道路是双向行驶的,沿着道路你可以到达任何一个城市.你有一个旅行计划,这个计划是从编号K的城市出发,每天到达一个你没有去过的城市, ...
- Extend Html.EditorFor MVC
原文发布时间为:2011-09-07 -- 来源于本人的百度文章 [由搬家工具导入] http://aspadvice.com/blogs/kiran/archive/2009/11/29/Addin ...
- cocos2d programming guide 翻译 引导页(完结)
http://bbs.tairan.com/article-25-1.html Cocos2d官方入门指导 原文地址:http://www.cocos2d-iphone.org/wiki/doku. ...
- shell编程学习笔记【原创】
本文为本人学习笔记,如有转载请注明出处,谢谢 一.Bourne Shell 有如下四种变量: 用户自定义变量 位置变量,即命令行参数 预定义变量 环境变量 二.位置变量 $ 与键入的命令行一样,包含脚 ...
- 网站开发只需数小时?Meteor 说这才是未来
原文: http://www.geekpark.net/topics/211573/ 那个想要挑战过去数十年沿用至今的网站开发模式的新势力来了. Meteor 是从 YC 孵化而出的现代网站开发平台, ...
- 关于CI框架加入sphinx官方API接口文件的时候,需要注意的问题
从sphinx下载的官方文件sphinxapi.php中类名为class SphinxClient 加入到CI框架,放在system/libraries/下,由于需要遵从CI框架libraries类名 ...
- 【原创】Oracle 11g R2 Client安装配置说明(多图详解)
1. 准备工作 安装Oracle11gR2client的时候,如果刚从网上下载的Oracle client,可能无法再2008 R2或者2012 R2的服务器上面运行. 报错:[INS-13001]环 ...
- [BZOJ3211]花神游历各国&&[BZOJ3038] 上帝造题的七分钟2 树状数组+并查集
3211: 花神游历各国 Time Limit: 5 Sec Memory Limit: 128 MBSubmit: 4057 Solved: 1480[Submit][Status][Discu ...