安卓客户端通过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. iphone CGBitmapContextCreate()函数解释

    http://blog.sina.com.cn/s/blog_3e50cef401019cd2.html CGContextRef CGBitmapContextCreate ( void *data ...

  2. Kubernetes网络配置

    #flannel#所有node都安装#下载https://github.com/coreos/flannel/releases#解压并把flanneld和mk-codker-opts.sh复制到/us ...

  3. block方法加入无效的问题

    +(LDLabel *)labelWithFrame:(CGRect)frame withTitle:(NSString *)title withFont:(float)font withtextCo ...

  4. 「kuangbin带你飞」专题十五 数位DP

    传送门 A.CodeForces - 55D Beautiful numbers 题意 一个正整数是 漂亮数 ,当且仅当它能够被自身的各非零数字整除.我们不必与之争辩,只需计算给定范围中有多少个漂亮数 ...

  5. uvalive4108(线段树)

    uvalive4108 题意 按顺序给出 n 个矩形,每给出一个矩形,统计它在多长的部分是最高的,并把这个长度称为该矩形的覆盖度,求最后总的覆盖度(每次得到的矩形的覆盖度之和) 分析 线段树.用两个数 ...

  6. 数学【p1412】 经营与开发(秦九韶算法)

    顾z 你没有发现两个字里的blog都不一样嘛 qwq 题目描述-->P1412 经营与开发 分析 虽然看到\(Rank_1\)已经有了解释. 但我认为我能BB的更好 我还是决定来写一篇题解. q ...

  7. centos忘记密码,重新设置密码的方法

    (1)重新启动Centos,在启动过程中,长按“ESC”键,进入GNU GRUB界面. (2)选择要进入的系统,按“E”键(在启动之前编辑命令). (3)选择第二项操作系统的内核“kernel”,按& ...

  8. javap -c 字节码含义

    aconst_null         将null对象引用压入栈 iconst_m1         将int类型常量-1压入栈 iconst_0         将int类型常量0压入栈 icons ...

  9. 【OpenJudge3531】【背包DP】【膜法交配律】判断整除

    判断整除 总时间限制: 1000ms 内存限制: 65536kB [描述] 一个给定的正整数序列,在每个数之前都插入+号或-号后计算它们的和.比如序列:1.2.4共有8种可能的序列:(+1) + (+ ...

  10. NDK安装教程 not a valid ndk directory -- Eclipse

    第一步:下载 Eclipse IDE for Java Developers http://www.eclipse.org/downloads/ 第二步:下载CDT http://www.eclips ...