安卓客户端通过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通信编程的更多相关文章

  1. Android Socket通信详解

    一.Socket通信简介  Android与服务器的通信方式主要有两种,一是Http通信,一是Socket通信.两者的最大差异在于,http连接使用的是“请求—响应方式”,即在请求时建立连接通道,当客 ...

  2. Android Socket 通信

    Android socket 通信 安卓编写Socket客户端,实现连接Socket服务端通信. 创建Socket连接并获取服务端数据 先创建几个全局变量吧 private BufferedWrite ...

  3. 【转】C# Socket通信编程

    https://www.cnblogs.com/dotnet261010/p/6211900.html#undefined 一:什么是SOCKET socket的英文原义是“孔”或“插座”.作为进程通 ...

  4. (转)android 蓝牙通信编程

    转自:http://blog.csdn.net/pwei007/article/details/6015907 Android平台支持蓝牙网络协议栈,实现蓝牙设备之间数据的无线传输. 本文档描述了怎样 ...

  5. linux系统socket通信编程实践

    简单介绍并实现了基于UDP(TCP)的windows(UNIX下流程基本一致)下的服务端和客户端的程序,本文继续探讨关于UDP编程的一些细节. 下图是一个简单的UDP客户/服务器模型: 我在这里也实现 ...

  6. linux系统socket通信编程详解函数

    linux socket编程之TCP与UDP   TCP与UDP区别 TCP---传输控制协议,提供的是面向连接.可靠的字节流服务.当客户和服务器彼此交换数据前,必须先在双方之间建立一个TCP连接,之 ...

  7. linux系统UDP的socket通信编程3

    我刚开始接触linux下的socket编程,边抄边理解udp socket编程,我的疑问是server不指定IP地址,client的目标IP地址是127.0.0.1,这样就可以通信吗?在同一主机下是不 ...

  8. linux系统socket通信编程2

    一.概述 TCP(传输控制协议)和UDP(用户数据报协议是网络体系结构TCP/IP模型中传输层一层中的两个不同的通信协议. TCP:传输控制协议,一种面向连接的协议,给用户进程提供可靠的全双工的字节流 ...

  9. linux系统socket通信编程1

    Linux下的Socket编程大体上包括Tcp Socket.Udp Socket即Raw Socket这三种,其中TCP和UDP方式的Socket编程用于编写应用层的socket程序,是我们用得比较 ...

随机推荐

  1. 从日升的mecha anime看mecha genre的衰退

    注:矢立肇是日升企画部集体笔名,如勇者系列便是公司企画 这里列出一些我看过认为有意思的动画,大抵同系列的就合并了,除非后续作品(剧场版,OVA,etc)并非直接剧情承接且有趣 注意我对长篇TV动画评价 ...

  2. Struts2---ActionContext和ServletActionContext小结

    转载自:http://www.cnblogs.com/tanglin_boy/archive/2010/01/18/1650871.html感谢原文作者的总结 1. ActionContext 在St ...

  3. 微信设置URL之WebApi方式

    微信公众号开发者设置里的URL,现在采用WebAPI的方式,结果一直报“未能正确设置Token”的错误,采用Handler和MVC的方式倒是可以. 解决步骤一,添加服务器IP到白名单. 解决步骤二,确 ...

  4. 自定义View Layout过程 (3)

    目录 目录 1. 知识基础 具体请看我写的另外一篇文章:(1)自定义View基础 - 最易懂的自定义View原理系列 2. 作用 计算View视图的位置. 即计算View的四个顶点位置:Left.To ...

  5. YYH的球盒游戏(NOIP模拟赛Round 6)

    题目描述 YYH有一些总共有种颜色的球,他有颜色的球个.他同样有个盒子,第个盒子能放个球. 他的目标是把这个球按规则放进个盒子里: 对于一个盒子,对于每种颜色的球至多只能放个. 把颜色为的球放进盒子, ...

  6. Linux内核内存管理-内存访问与缺页中断【转】

    转自:https://yq.aliyun.com/articles/5865 摘要: 简单描述了x86 32位体系结构下Linux内核的用户进程和内核线程的线性地址空间和物理内存的联系,分析了高端内存 ...

  7. zabbix 硬盘健康监控

    #!/bin/sh function sh { sd=`ls /dev/ | grep '^sd' |grep -v '[0-9]$'` echo '' > /usr/local/zabbix/ ...

  8. appium+python自动化26-模拟手势点击坐标(tap)【转载】

    ​# 前言:有时候定位元素的时候,你使出了十八班武艺还是定位不到,怎么办呢?(面试经常会问)那就拿出绝招:点元素所在位置的坐标 tap用法 1.tap是模拟手指点击,一般页面上元素的语法有两个参数,第 ...

  9. MVC如何在路由器(RouteConfig)定义后缀.html

    一.配置文件web.config添加一下设置 <system.webServer> <modules runAllManagedModulesForAllRequests=" ...

  10. C#集合类:动态数组、队列、栈、哈希表、字典(转)

    1.动态数组:ArrayList 主要方法:Add.AddRange.RemoveAt.Remove 2.队列:Queue 主要方法:Enqueue入队列.Dequeue出队列.Peek返回Queue ...