安卓客户端通过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. Topcoder SRM 602 div1题解

    打卡- Easy(250pts): 题目大意:rating2200及以上和2200以下的颜色是不一样的(我就是属于那个颜色比较菜的),有个人初始rating为X,然后每一场比赛他的rating如果增加 ...

  2. 编写Shell脚本的最佳实践,规范二

    需要养成的习惯如下: 代码有注释 #!/bin/bash # Written by steven # Name: mysqldump.sh # Version: v1.0 # Parameters : ...

  3. poj 3071 Football (概率DP水题)

    G - Football Time Limit:1000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u Submit ...

  4. SQL Server 及 Visual Studio的离线帮助文档

    1>Sql Server帮助文档下载:地址 2>Visual Studion帮助文档下载:地址 3>安装Help Viewer 4>浏览到刚才下载的文件处进行安装 4>设 ...

  5. Apache二级域名实现

    Apache二级域名实现 首先,你的拥有一个有泛域名解析的顶级域名,例如: domain.com 其次,在 httpd.conf 中打开 mod_rewrite 之后,在 httpd.conf 的最后 ...

  6. [LA_3938]最大连续动态和

    Sample Input 3 1 1 2 3 1 1 Sample Output Case 1: 1 1 线段树 L,R表示该区间的左右端点,sum表示该区间值的总和 l,r表示该区间连续的最大和的左 ...

  7. mysql 连接失败问题汇集

    FHost '192.168.5.128' is not allowed to connect to this MySQL serverConnection closed by foreign hos ...

  8. cocos2d学习网址

    http://python.cocos2d.org/doc/programming_guide/index.html http://bbs.tairan.com/article-25-1.html h ...

  9. 华为上机测试题(求亮灯数量-java)

    PS:自己写的,自测试OK,供大家参考. /* 一条长廊里依次装有n(1 ≤ n ≤ 65535)盏电灯,从头到尾编号1.2.3.…n-1.n.每盏电灯由一个拉线开关控制.开始,电灯全部关着.有n个学 ...

  10. Spring与Struts2的整合

    一.复制jar文件. 把struts2-spring-plugin-..*.jar和spring.jar复制到Web工程的WEB-INF/lib目录下,并且还需要复制commons-logging.j ...