import java.io.DataInputStream;
import java.io.IOException;
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; import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log; @SuppressLint("NewApi")
public class SocketTCPServer implements Runnable
{
private String tag="SocketTCPServer";
//服务器端口
private final int SERVERPORT = 5111;
//存储所有客户端Socket连接对象
public List<Socket> mClientList = new ArrayList<Socket>();
//线程池
private ExecutorService mExecutorService;
//ServerSocket对象
private ServerSocket mServerSocket;
private PrintWriter mPrintWriter;
private String mStrMSG;
public SocketTCPServer()
{
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
StartServer();
handler.postDelayed(runnable, DELYED); //启动定时器
}
//接收线程发送过来信息,并用TextView显示
public Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg); Log.e(tag,mStrMSG); }
};
//每个客户端单独开启一个线程
class ThreadServer implements Runnable
{
private Socket mSocket;
private DataInputStream dinput;
public ThreadServer(Socket socket)
{
try{
this.mSocket = socket;
dinput = new DataInputStream(socket.getInputStream());
SendToClient("hello,tcp server...");
}
catch(Exception e){
Log.e(tag, e.toString());
} }
public void run()
{
try
{
byte[] bbuf = new byte[10000];
while (true) { if (!mSocket.isClosed()) {
if (mSocket.isConnected()) {
if (!mSocket.isInputShutdown()) {
int length = dinput.read(bbuf);
mStrMSG = new String(bbuf, 0, length, "gb2312");
mStrMSG += "\n";
Log.e(tag, mStrMSG);
mHandler.sendMessage(mHandler.obtainMessage());
}
}
}
}
}
catch (IOException e)
{
Log.e(tag, e.toString());
}
}
}
public void run() {
Socket client = null;
try{
while (true)
{
Log.e(tag, "收到客户端连接。。。");
//接收客户连接并添加到list中
client = mServerSocket.accept();
mClientList.add(client);
//开启一个客户端线程
if(client!=null){
//异常捕不到,客户端退出后,程序挂了
mExecutorService.execute(new ThreadServer(client));
} }
}
catch(Exception e){
mClientList.remove(client);
Log.e(tag, e.toString());
}
}
/**
* 向客户端发送消息
* @param msg
*/
public void SendToClient(String msg){
try{
if(mClientList.size()>0){
for (Socket client : mClientList)
{
mPrintWriter = new PrintWriter(client.getOutputStream(), true);
mPrintWriter.println(msg);
}
}
}
catch(Exception e){
Log.e("向客户端发送消息败了", e.toString());
StartServer();//消息发送失败,重启服务器
}
}
public void StartServer(){
try
{
if(mServerSocket!=null){
mServerSocket.close();
}
//设置服务器端口
mServerSocket = new ServerSocket(SERVERPORT);
//创建一个线程池
mExecutorService = Executors.newCachedThreadPool();
//用来临时保存客户端连接的Socket对象
new Thread(SocketTCPServer.this).start();
}
catch (IOException e)
{
Log.e(tag, e.toString());
} }
public void CloseServer(){
try {
mServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
} //定時器
private int DELYED= 5000;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
handler.postDelayed(this, DELYED);
SendToClient("this message from server:dongdongdong");
} catch (Exception e) {
Log.e(tag+"->runnable定时器", e.toString());
}
}
};
}

客户端

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 com.onesuncomm.model.CurrentUserInfo;
import com.onesuncomm.utils.DateUtil;
import com.onesuncomm.w511.MainActivity;
import com.onesuncomm.w511.TabCorePlateLocateActivity;
import com.onesuncomm.w511.TabServerLogActivity; import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log; @SuppressLint("NewApi")
public class SocketTCPClient implements Runnable {
private static SocketTCPClient mobileSocket;
private static String Tag="SocketTCPClient"; private Socket socket = null;
private BufferedReader in = null;
private PrintWriter out = null;
private String content = "";
public SocketTCPClient(){
try {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
handler.postDelayed(runnable, DELYED); //启动定时器 } catch (Exception ex) {
Log.e(Tag+"->SocketTCPClient", ex.getMessage());
CurrentUserInfo.SocketStatus=false;
}
}
public static final SocketTCPClient instanceMobileSocket(){
synchronized (SocketTCPClient.class) {
if(mobileSocket==null) {
mobileSocket = new SocketTCPClient();
}
}
return mobileSocket;
}
public void ConnectionService(){
try { if(socket!=null){
socket.close();
}
socket = new Socket(CurrentUserInfo.server_ip, Integer.parseInt(CurrentUserInfo.server_port));
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
CurrentUserInfo.SocketStatus=true;
//启动线程,接收服务器发送过来的数据
new Thread(SocketTCPClient.this).start();
}
catch (IOException ex) {
CurrentUserInfo.SocketStatus=false;
}
}
//接收线程发送过来信息
public Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
//处理接收的信息
TabServerLogActivity.AddToLog("接收("+DateUtil.GetNowDateString()+"):"+content);
if(content.contains("Z0")){
sendMsgToServer("Z0\r\n");
}
if(MainActivity.isNetworkAvailable()){
//todo: 若返回lac,Cell则从服务器查询基站信息并显示在地图上
}
else{ }
//CurrentUserInfo.sbLog.append(content);
}
};
/*
* 读取服务器发来的信息,并通过Handler发给UI线程
*/
public void run() {
try {
char [] bbuf = new char[10000];
StringBuilder temp = new StringBuilder();
while (true) {
if (!socket.isClosed()) {
if (socket.isConnected()) {
CurrentUserInfo.SocketStatus=true;
timeOut=0;
if (!socket.isInputShutdown()) {
int leng=in.read(bbuf);
content = new String(bbuf, 0, leng);
temp.append(content);
//if (temp.toString().contains("Z")){
content=temp.toString();
temp =new StringBuilder();
mHandler.sendMessage(mHandler.obtainMessage());
//}
CurrentUserInfo.SocketStatus=true;
}
}
}
}
} catch (Exception e) {
CurrentUserInfo.SocketStatus=false;
Log.e(Tag+"->run()", e.getMessage());
}
} public void sendMsgToServer(Object msg){
if (socket.isConnected()) {
if (!socket.isOutputShutdown()) {
out.println(msg);
TabServerLogActivity.AddToLog("发送("+DateUtil.GetNowDateString()+"):"+msg);
}
}
}
//定時器
private int DELYED= 1000;
private int timeOut=0;
private int timeSendZ3=0;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
handler.postDelayed(this, DELYED);
timeOut++;
timeSendZ3++;
if (socket==null||socket.isOutputShutdown()||!CurrentUserInfo.SocketStatus||!socket.isConnected()) {
CurrentUserInfo.SocketStatus=false;
new Thread() {
public void run() {
ConnectionService();
};
}.start();
} TabCorePlateLocateActivity.setSocketStatus(); } catch (Exception e) {
Log.e(Tag+"->runnable定时器", e.toString());
}
}
};
}

调用

/**
* 开启socket
*/
private void openSocket(){
try{
//SocketTCPServer server =new SocketTCPServer();
//server.SendToClient("本消息来自服务器");
final SocketTCPClient tcp =SocketTCPClient.instanceMobileSocket();
new Thread() {
public void run() {
tcp.ConnectionService();
};
}.start();
}
catch(Exception ex){
LogUtil.WriteError(ex);
}
}

Android之socket服务端的更多相关文章

  1. Android版Ftp服务端软件

    分享一款开发的Android版Ftp服务端软件,支持Android4.0及以上版本,可以实现局域网无线传输文件到手机,或者把手机上的多媒体文件分享到iPad等设备来扩展这些设备的存储空间,详情请见软件 ...

  2. Android客户端与服务端交互之登陆示例

    Android客户端与服务端交互之登陆示例 今天了解了一下android客户端与服务端是怎样交互的,发现其实跟web有点类似吧,然后网上找了大神的登陆示例,是基于IntentService的 1.后台 ...

  3. 在python中编写socket服务端模块(二):使用poll或epoll

    在linux上编写socket服务端程序一般可以用select.poll.epoll三种方式,本文主要介绍使用poll和epoll编写socket服务端模块. 使用poll方式的服务器端程序代码: i ...

  4. AutoCAD.net支持后台线程-Socket服务端

    最近因为公司项目的需求,CAD作为服务端在服务器中常驻运行,等待客户端远程发送执行任务的指令,最终确认用Socket-tcp通讯,CAD需要实时监听客户端发送的消息,这时就需要开启线程执行Socket ...

  5. 使用NewLife网络库构建可靠的自动售货机Socket服务端(一)

    最近有个基于tcp socket 协议和设备交互需求,想到了新生命团队的各种组件,所以决定用NewLife网络库作为服务端来完成一系列的信息交互. 第一,首先说一下我们需要实现的功能需求吧 1,首先客 ...

  6. 第一个socket服务端程序

    第一个socket服务端程序 #include <stdio.h> #include <stdlib.h> #include <string.h> #include ...

  7. Android 小例子服务端

    这是之前发布的Android项目的服务端源码,只是简单的根据请求返回了一些测试数据,没有实现对数据库的操作,可以根据需求自己实现. 这是mvc4 WebAPI项目,需要用vs2012打开. 如果是用的 ...

  8. C# Socket服务端与客户端通信(包含大文件的断点传输)

    步骤: 一.服务端的建立 1.服务端的项目建立以及页面布局 2.各功能按键的事件代码 1)传输类型说明以及全局变量 2)Socket通信服务端具体步骤:   (1)建立一个Socket   (2)接收 ...

  9. MSDN上的异步socket 服务端例子

    MSDN上的异步socket 服务端例子 2006-11-22 17:12:01|  分类: 代码学习 |  标签: |字号大中小 订阅     Imports SystemImports Syste ...

随机推荐

  1. leetcode 22括号生成

    非常好的一道题.一开始的思想是这样的,先把n对括号按照某一顺序生成一个string,然后用全排列算法生成所有可能,然后利用stack写一段判断括号是否匹配的字符串,匹配的假如结果中.不过会超时.因为全 ...

  2. .net委托链

    委托链可以增加方法,可以移除方法,如果是无返回值的方法,我们把它们都绑定到一个委托上面的话,直接调用,那么调用此委托就会依次调用其中的方法:但是如果是多个有返回值的委托链,如果我们不采用特殊手段,直接 ...

  3. mybatis核心文件详解

    MyBatis配置文件详解 configuration  这是配置文件的根元素标签,所有的其他元素都要在这个标签下使用. environments   用于管理所有环境,并可以指定默认使用哪个环境,通 ...

  4. HTTP请求解析过程 (简单概括)

    1.域名解析 用户输入网址,由域名系统DNS解析输入的网址: 2.TCP的3次握手 通过域名解析出的IP地址来向web服务器发起TCP连接请求,如果3次握手通过,则与web服务端建立了可靠的连接: 3 ...

  5. 编写带有下列声明的例程:第一个例程是个驱动程序,它调用第二个例程并显示String str中的字符的所有排列。例如,str是"abc", 那么输出的串则是abc,acb,bac,bca,cab,cba,第二个例程使用递归。

    全排列在笔试面试中很热门,因为它难度适中,既可以考察递归实现,又能进一步考察非递归的实现,便于区分出考生的水平.所以在百度和迅雷的校园招聘以及程序员和软件设计师的考试中都考到了,因此本文对全排列作下总 ...

  6. sql 查询重复数据,删除重复数据,过滤重复数据

    select * from (SELECT titleid,count(titleid) c FROM [DragonGuoShi].[dbo].[ArticleInfo] group by titl ...

  7. HDU 6300

    Problem Description Chiaki has 3n points p1,p2,…,p3n. It is guaranteed that no three points are coll ...

  8. C++的类型转换

    一.类型转换名称和语法 1.C风格的强制类型转换(Type Cast)很简单,不管什么类型的转换统统是: TYPE b = (TYPE)a    2.C++风格的类型转换提供了4种类型转换操作符来应对 ...

  9. python: numpy--函数 shape用法

    http://blog.csdn.net/u010758410/article/details/71554224 shape函数是numpy.core.fromnumeric中的函数,它的功能是查看矩 ...

  10. Python - 1. Built-in Atomic Data Types

    From:http://interactivepython.org/courselib/static/pythonds/Introduction/GettingStartedwithData.html ...