多线程socket编程示例
工程:
代码:
package com.my.socket.business; /**
* 业务实现类
*
* @author ZY
*
*/
public class CoreMisBusinessImpl implements IBusiness { @Override
public String doBusiness(String requestJsonMsg) {
System.out.println("收到数据[" + requestJsonMsg + "]"); // TODO 业务处理
System.out.println("已处理数据"); // 返回业务数据(Json形式)
String resJson = "{\"markId\":1,\"ID\":\"02\",\"goods_id\":\"1\",\"markContent\":\"成功\",\"userNickname\":\"hello\"}"; System.out.println("已返回数据"); return resJson;
}
}
package com.my.socket.business; public interface IBusiness { public String doBusiness(String requestJsonMsg); }
package com.my.socket.common; import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket; /**
* socket发送端
*
* @author ZY
*
*/
public class Client { /**
* 发送socket请求,返回服务器处理结果字符串
*
* @param ip
* @param port
* @param timeout
* @param requestJsonMsg
* @return
* @throws IOException
*/
public static String sendSocketRequest(String ip, int port, int timeout, String requestJsonMsg) throws IOException {
String res = null;
Socket socket = null;
BufferedReader br = null;
BufferedWriter out = null;
try {
socket = new Socket(ip, port);
socket.setSoTimeout(timeout);
System.out.println("现在客户端发起了一个socket请求,客户端[ip=" + socket.getLocalAddress() + ",port=" + port + "],服务端[ip="
+ ip + ",port=" + port + "]"); // 发送消息
requestJsonMsg = requestJsonMsg + Constant.LINESEPARATOR;
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), Constant.CHARCODE_UTF8));
out.write(requestJsonMsg);
out.flush();
// 接收服务器的反馈
br = new BufferedReader(new InputStreamReader(socket.getInputStream(), Constant.CHARCODE_UTF8));
res = br.readLine(); } catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
if (socket != null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} return res;
} public static void main(String[] args) throws IOException { String ip = "10.5.109.184";
int port = 8088;
int timeout = 1000 * 60 * 5;
String requestJsonMsg = "{\"markId\":1,\"ID\":\"02\",\"goods_id\":\"1\",\"markContent\":\"测试\",\"userNickname\":\"hello\"}"; String res = sendSocketRequest(ip, port, timeout, requestJsonMsg); System.out.println("res=" + res);
}
}
package com.my.socket.common; public class Constant { /**
* 编码方式
*/
public static final String CHARCODE_UTF8 = "utf-8"; /**
* 文件换行符
*/
public static final String LINESEPARATOR = System.getProperty("line.separator"); }
package com.my.socket.common; import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket; import com.my.socket.business.IBusiness; class Handler implements Runnable { private Socket socket; private IBusiness business; public Handler(Socket socket,IBusiness business) {
this.socket = socket;
this.business = business;
} private BufferedWriter getWriter(Socket socket) throws IOException {
return new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream(), Constant.CHARCODE_UTF8));
} private BufferedReader getReader(Socket socket) throws IOException {
InputStream socketIn = socket.getInputStream();
return new BufferedReader(new InputStreamReader(socketIn,
Constant.CHARCODE_UTF8));
} public void run() {
BufferedReader br = null;
BufferedWriter out = null;
try {
br = getReader(socket);
out = getWriter(socket);
String requestJsonMsg = null;
while ((requestJsonMsg = br.readLine()) != null) {
// 业务处理:接收到请求消息,处理后,返回消息
String responseJsonMsg = business.doBusiness(requestJsonMsg);
responseJsonMsg = responseJsonMsg + Constant.LINESEPARATOR;
out.write(responseJsonMsg);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (socket != null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (out != null)
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.my.socket.common; import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import com.my.socket.business.CoreMisBusinessImpl;
import com.my.socket.business.IBusiness; /**
* 数据同步服务:可用于前置和核心mis,根据实例化参数配置<br>
* 注意:本实例只有一个
*
* @author zhangyi
*
*/
public class MultiThreadServer extends Thread {
private static MultiThreadServer server;
private ServerSocket serverSocket;
private ExecutorService executorService;
private final int POOL_SIZE = 10;
private int port;
// 业务business
private IBusiness business; public int getPort() {
return port;
} public void setPort(int port) {
this.port = port;
} public IBusiness getBusiness() {
return business;
} public void setBusiness(IBusiness business) {
this.business = business;
} private MultiThreadServer() {
} public static MultiThreadServer getInstance() {
if (null == server) {
server = new MultiThreadServer();
}
return server;
} private void init(int port) throws IOException {
serverSocket = new ServerSocket(port);
executorService = Executors.newFixedThreadPool(Runtime.getRuntime()
.availableProcessors()
* POOL_SIZE);
System.out.println("socket同步服务已启动...");
} private void startExecute() {
while (true) {
Socket socket = null;
try {
socket = serverSocket.accept();
executorService.execute(new Handler(socket, business)); } catch (Exception e) {
e.printStackTrace();
}
}
} /**
* 入口方法<br>
* 一个核心mis只有一个ip和端口
*
*/
@Override
public void run() { try {
server.init(port);
server.startExecute();
} catch (IOException e) {
e.printStackTrace();
} } public static void main(String[] args) {
// 必须是单例的
MultiThreadServer server = MultiThreadServer.getInstance(); IBusiness coreMisBusiness = new CoreMisBusinessImpl(); int port = 8088; server.setBusiness(coreMisBusiness);
server.setPort(port); Thread th = new Thread(server);
th.start();
System.out.println("服务已启动...");
}
}
多线程socket编程示例的更多相关文章
- 多线程Java Socket编程示例
package org.merit.test.socket; import java.io.BufferedReader; import java.io.IOException; import jav ...
- 多线程异步编程示例和实践-Task
上篇博文中,我们介绍了Thread和ThreadPool: 多线程异步编程示例和实践-Thread和ThreadPool 本文中我们继续,说一下TPL(Task Parallel Library, 简 ...
- Java Socket编程示例
一.Socket简介: 1.什么是Socket 网络上的两个程序通过一个双向的通讯连接实现数据的交换,这个双向链路的一端称为一个Socket.Socket通常用来实现客户方和服务方的连接.Socket ...
- 使用libevent进行多线程socket编程demo
最近要对一个用libevent写的C/C++项目进行修改,要改成多线程的,故做了一些学习和研究. libevent是一个用C语言写的开源的一个库.它对socket编程里的epoll/select等功能 ...
- 多线程异步编程示例和实践-Thread和ThreadPool
说到多线程异步编程,总会说起Thread.ThreadPool.Task.TPL这一系列的技术.总结整理了一版编程示例和实践,分享给大家. 先从Thread和ThreadPool说起: 1. 创建并启 ...
- day08 多线程socket 编程,tcp粘包处理
复习下socket 编程的步骤: 服务端: 1 声明socket 实例 server = socket.socket() #括号里不写 默认地址簇使用AF_INET 即 IPv4 ...
- Linux socket编程示例(最简单的TCP和UDP两个例子)
一.socket编程 网络功能是Uinux/Linux的一个重要特点,有着悠久的历史,因此有一个非常固定的编程套路. 基于TCP的网络编程: 基于连接, 在交互过程中, 服务器和客户端要保持连接, 不 ...
- Python Socket 编程示例 Echo Server
简评:我们已经从「Python Socket 编程概览」了解了 socket API 的概述以及客户端和服务器的通信方式,接下来让我们创建第一个客户端和服务器,我们将从一个简单的实现开始,服务器将简单 ...
- 多线程Java Socket编程示例(转)
这篇做为学习孙卫琴<<Java网络编程精解>>的学习笔记吧.其中采用Java 5的ExecutorService来进行线程池的方式实现多线程,模拟客户端多用户向同一服务器端发送 ...
随机推荐
- Linux 查杀进程
ps -eaf |grep "stoporder.php" | grep -v "grep"| awk '{print $2}'|xargs kill -9 # ...
- AngularJs的$http使用随笔
AngularJs的$http服务是Angularjs自带的核心服务之一,用来与HTTP远程服务器交互. 关于$http使用,我体会的一下几点注意: 1.在使用是报“Uncaught Referenc ...
- 并查集 Union-Find
并查集能做什么? 1.连接两个对象; 2.查询两个对象是否在一个集合中,或者说两个对象是否是连接在一起的. 并查集有什么应用? 1. Percolation问题. 2. 无向图连通子图个数 3. 最近 ...
- Controller将Model数据传给View层,View层应该如何处理?
首先,我们在Model层中添加一个Person类. namespace MVCTest.Models{ public class Person { public string ...
- (算是dp吧) 小茗的魔法阵 (fzu 2225)
http://acm.fzu.edu.cn/problem.php?pid=2225 Problem Description 在打败了易基•普罗布朗.诺姆•普罗布朗之后,小茗同学开始挑战哈德•普罗 ...
- android和ubifs
原文地址: http://opendevkit.com/?e=37 1. ubifs号称性能比yaffs2 好,同时压缩可读写,文件系统image体较小同时可写,相当不错 2. ubifs制作 (1) ...
- 工具武装的前端开发工程师 Mac 软件清单
Awesome Mac 这个仓库主要是收集非常好用的Mac应用程序.软件以及工具,主要面向开发者和设计师.有这个想法是因为我最近发了一篇较为火爆的涨粉儿微信公众号文章<工具武装的前端开发工程 ...
- 工资低的.Net程序员,活该你工资低
这两天博客园上关于“.Net工资低”的讨论挺多的,让我不禁想起一句话“拉不出屎来怪地球没引力”. 那些抱怨“做.Net工作三年了月薪才6千,我的同学做Java现在都一万二”的哥们,你问问自己“我会什么 ...
- zlib的安装
wget http://www.zlib.net/zlib-1.2.8.tar.gz tar -zxvf zlib-1.2.8.tar.gz cd zlib-1.2.8 ./configure mak ...
- 用c#开发微信(1)服务号的服务器配置和企业号的回调模式 - url接入 (源码下载)
最近研究了下服务号的服务器配置和企业号的回调模式.真正实现完后,觉得很简单,但一开始还是走了点弯路,所以写了个web程序,只用改下配置文件里的参数就可以直接用了.下面介绍下详细的用法以及实现步骤. 本 ...