diff --git a/Demo/.classpath b/Demo/.classpath
new file mode 100644
index 0000000..00fcd0b
--- /dev/null
+++ b/Demo/.classpath
@@ -0,0 +1,28 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/Demo/src/Number1.java b/Demo/src/Number1.java
new file mode 100644
index 0000000..c6a0542
--- /dev/null
+++ b/Demo/src/Number1.java
@@ -0,0 +1,12 @@
+
+public class Number1 {
+ public static void main(String[] args) {
+ String a="1";
+ String b="2";
+ System.out.println(a+b);
+ String areaCode="00";
+ int areaCodeInt =Integer.parseInt(areaCode.substring(1,areaCode.length()));
+ System.out.println(areaCodeInt);
+ }
+
+}
diff --git a/Demo/src/config.properties b/Demo/src/config.properties
new file mode 100644
index 0000000..74491d5
--- /dev/null
+++ b/Demo/src/config.properties
@@ -0,0 +1,3 @@
+user=i'm user
+pwd=i'm pwd
+fileViewPath=http://www.baidu.com
\ No newline at end of file
diff --git a/Demo/src/exception/Exceptions.java b/Demo/src/exception/Exceptions.java
new file mode 100644
index 0000000..afe75af
--- /dev/null
+++ b/Demo/src/exception/Exceptions.java
@@ -0,0 +1,26 @@
+package exception;
+
+public class Exceptions {
+ public static String result(int a,int b){
+ try{
+ a=a/b;
+ }catch(Exception e){
+ return "0";
+ }
+ System.out.println("hello");
+ return "1";
+ }
+ public static String isTrue(){
+ int a=4;
+ if(a==5){
+ return "true";
+ }
+ System.out.println("你好");
+ return "false";
+ }
+ public static void main(String[] args) {
+ //System.out.println(result(4,0));
+ System.out.println(isTrue());
+ }
+
+}
diff --git a/Demo/src/exe/UpCase.java b/Demo/src/exe/UpCase.java
new file mode 100644
index 0000000..9ec85db
--- /dev/null
+++ b/Demo/src/exe/UpCase.java
@@ -0,0 +1,21 @@
+package exe;
+
+public class UpCase {
+ public static String upcase(String s){
+ String x=s.toUpperCase();
+ return x;
+ }
+ public static String lowcase(String s){
+ String x=s.toLowerCase();
+ return x;
+ }
+ public static void main(String[] args) {
+ String s="wweddd";
+ String xx=upcase(s);
+ System.out.println(xx);
+ String s1="WWDWDE";
+ String xx1=lowcase(s1);
+ System.out.println(xx1);
+ }
+
+}
diff --git a/Demo/src/exe/Yang.java b/Demo/src/exe/Yang.java
new file mode 100644
index 0000000..f1c5598
--- /dev/null
+++ b/Demo/src/exe/Yang.java
@@ -0,0 +1,28 @@
+package exe;
+
+/**
+ * @author mercy
+ *一只羊,4年后每年生一只,求N年生多少只?
+ */
+public class Yang {
+ public static int getYang(int n){
+ int sum=0;
+ if(n<3){
+ return 0;
+ }else{
+ int m=n/3;
+ for(int i=1;i<=m;i++){
+ sum+=n-(3*i);
+ }
+ }
+ return sum;
+
+
+ }
+
+ public static void main(String[] args) {
+ int n=10;
+ System.out.println(getYang(n));
+ }
+
+}
diff --git a/Demo/src/file/Args.java b/Demo/src/file/Args.java
new file mode 100644
index 0000000..232f20d
--- /dev/null
+++ b/Demo/src/file/Args.java
@@ -0,0 +1,10 @@
+package file;
+
+public class Args {
+ public static void main(String[] args) {
+ for(int i=0;i map=new HashMap<>();
+ for(int i=0;i map=new HashMap<>();
+ for(int i=0;i list=new ArrayList();
+ List lists=new ArrayList();
+ for(int i=1;i<10;i++){
+ list.add(i);
+ }
+ lists.addAll(list);
+ List list1=new ArrayList();
+ //lists.addAll(list1);
+ System.out.println(lists.size());
+ for(int i=0;i us=new ArrayList();
+ User u=new User("A",1);
+ us.add(u);
+ u=new User("C",2);
+ us.add(u);
+ u=new User("D",5);
+ us.add(u);
+ u=new User("A",4);
+ us.add(u);
+ u=new User("D",6);
+ us.add(u);
+ Map map1=new HashMap();
+ for(int i=0;i entry : map1.entrySet())
+ {
+ System.out.println(entry.getKey()+": "+entry.getValue());
+ }
+ }
+
+}
diff --git a/Demo/src/list/ListList.java b/Demo/src/list/ListList.java
new file mode 100644
index 0000000..1cd3a92
--- /dev/null
+++ b/Demo/src/list/ListList.java
@@ -0,0 +1,18 @@
+package list;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ListList {
+ public static void main(String[] args) {
+ List list=new ArrayList();
+ List list1=new ArrayList();
+ list.add("aa");list.add("cc");list.add("bb");
+ list.addAll(list1);
+ System.out.println(list.size());
+ for(String i:list){
+ System.out.println(i);
+ }
+ }
+
+}
diff --git a/Demo/src/list/ListNull.java b/Demo/src/list/ListNull.java
new file mode 100644
index 0000000..2bb1c9e
--- /dev/null
+++ b/Demo/src/list/ListNull.java
@@ -0,0 +1,17 @@
+package list;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ListNull {
+ public static void main(String[] args) {
+ List list=new ArrayList();
+ if(list!=null&&!list.isEmpty()){
+ System.out.println("不为空");
+ System.out.println(list.get(0));
+ }else{
+ System.out.println("空");
+ }
+ }
+
+}
diff --git a/Demo/src/list/ListSeq.java b/Demo/src/list/ListSeq.java
new file mode 100644
index 0000000..45d3d97
--- /dev/null
+++ b/Demo/src/list/ListSeq.java
@@ -0,0 +1,34 @@
+package list;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+public class ListSeq {
+ public static void main(String[] args) {
+ List list1=new ArrayList();
+ for(int i=0;i<5;i++){
+ User user=new User();
+ user.setAge(i);
+ user.setId(i);
+ user.setName("age"+i);
+ list1.add(user);
+ }
+ Collections.sort(list1, new Comparator() {// 排序
+ @Override
+ public int compare(User o1, User o2) {
+ if (o1.getAge()==null) {
+ o1.setAge(1000);
+ }
+ if (o2.getAge()== null) {
+ o2.setAge(1000);
+ }
+ //return o2.getAge().compareTo(o1.getAge());//倒序
+ return o1.getAge().compareTo(o2.getAge());//顺序
+ }
+ });
+ System.out.println(list1.get(1).getAge());//顺序是1,倒序是3
+ }
+
+}
diff --git a/Demo/src/list/ListTest.java b/Demo/src/list/ListTest.java
new file mode 100644
index 0000000..50ac07b
--- /dev/null
+++ b/Demo/src/list/ListTest.java
@@ -0,0 +1,24 @@
+package list;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class ListTest {
+ public static void main(String[] args) {
+ List users=new ArrayList();
+ User user2=new User();
+ user2.setAge(1);
+ for(int i=0;i<10;i++){
+ User user=new User();
+ user.setAge(i);
+ user.setName("name"+i);
+ users.add(user);
+ }
+ System.out.println(users.toString());
+ for(User user1:users){
+ System.out.println(user1.getAge()+"====="+user1.getName());
+ }
+
+ }
+
+}
diff --git a/Demo/src/list/MyList.java b/Demo/src/list/MyList.java
new file mode 100644
index 0000000..4b9219e
--- /dev/null
+++ b/Demo/src/list/MyList.java
@@ -0,0 +1,22 @@
+package list;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class MyList {
+ public static void main(String[] args) {
+ List list1=new ArrayList();
+ List list2=new ArrayList();
+ list1.add("a");list1.add("b");list1.add("c");
+ list2.add("1");list2.add("2");list2.add("3");list2.add("4");
+ List> ls=new ArrayList>();
+ ls.add(list1);
+ ls.add(list2);
+ for(int i=0;i ulist=new ArrayList();
+ for(int i=0;i<10;i++){
+ User user=new User();
+ user.setAge(i);
+ user.setId(i+1);
+ ulist.add(user);
+ }
+ System.out.println(ulist.get(0).getAge()+ulist.get(0).getName()+ulist.get(0).getId());
+ for(User user1:ulist){
+ user1.setName(user1.getAge()+"name");
+ }
+ for(int i=0;i
+
+
+
+
+
diff --git a/NetWork/.gitignore b/NetWork/.gitignore
new file mode 100644
index 0000000..ae3c172
--- /dev/null
+++ b/NetWork/.gitignore
@@ -0,0 +1 @@
+/bin/
diff --git a/networkProgramming/.project b/NetWork/.project
similarity index 87%
rename from networkProgramming/.project
rename to NetWork/.project
index 26c1cd5..ec02c8b 100644
--- a/networkProgramming/.project
+++ b/NetWork/.project
@@ -1,6 +1,6 @@
- networkProgramming
+ NetWork
diff --git a/networkProgramming/.settings/org.eclipse.jdt.core.prefs b/NetWork/.settings/org.eclipse.jdt.core.prefs
similarity index 74%
rename from networkProgramming/.settings/org.eclipse.jdt.core.prefs
rename to NetWork/.settings/org.eclipse.jdt.core.prefs
index 838bd9d..bb35fa0 100644
--- a/networkProgramming/.settings/org.eclipse.jdt.core.prefs
+++ b/NetWork/.settings/org.eclipse.jdt.core.prefs
@@ -1,11 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.7
+org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.source=1.7
+org.eclipse.jdt.core.compiler.source=1.8
diff --git a/networkProgramming/src/start/EchoPlayer.java b/NetWork/src/demo1/EchoPlayer.java
similarity index 84%
rename from networkProgramming/src/start/EchoPlayer.java
rename to NetWork/src/demo1/EchoPlayer.java
index 67fe1bb..d8da1a5 100644
--- a/networkProgramming/src/start/EchoPlayer.java
+++ b/NetWork/src/demo1/EchoPlayer.java
@@ -1,9 +1,13 @@
-package start;
+package demo1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
+/**
+ * @author mercy
+ * 输入字符串,并输出
+ */
public class EchoPlayer {
public static String echo(String msg){
return "echo:"+msg;
diff --git a/README.md b/README.md
deleted file mode 100644
index 4f29390..0000000
--- a/README.md
+++ /dev/null
@@ -1,2 +0,0 @@
-# java-network-programming
-《java网络编程精解》练习题
diff --git a/networkProgramming/.classpath b/networkProgramming/.classpath
deleted file mode 100644
index e1d87d8..0000000
--- a/networkProgramming/.classpath
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
-
-
-
-
-
-
-
-
diff --git a/networkProgramming/src/cindy/CindyServer.java b/networkProgramming/src/cindy/CindyServer.java
deleted file mode 100644
index 60e5965..0000000
--- a/networkProgramming/src/cindy/CindyServer.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package cindy;
-
-import net.sf.cindy.Message;
-import net.sf.cindy.Session;
-import net.sf.cindy.SessionAdapter;
-import net.sf.cindy.impl.AutoCloseEventGenerator;
-import net.sf.cindy.impl.SimpleServerSocketSession;
-//参考 http://blog.csdn.net/kjfcpua/article/details/4890540
-public class CindyServer {
- public static void main(String[] args) {
- //建立一个普通的TCP服务
- SimpleServerSocketSession session = new SimpleServerSocketSession();
- //设置事件产生器,如果和上面一段程序一起运行,应该共享同一个事件产生器以提高效率
- session.setEventGenerator(new AutoCloseEventGenerator());
- //设置要监听的端口
- session.setListenPort(10003);
- //添加连接上SocketSession的事件监听器
- session.addSocketSessionListener(new SessionHandler());
- //开始服务
- session.start(true ) ;
- System.out.println("服务已经启动");
- }
-}
diff --git a/networkProgramming/src/cindy/SessionHandler.java b/networkProgramming/src/cindy/SessionHandler.java
deleted file mode 100644
index 43b1f70..0000000
--- a/networkProgramming/src/cindy/SessionHandler.java
+++ /dev/null
@@ -1,53 +0,0 @@
-package cindy;
-
-import java.nio.ByteBuffer;
-
-import net.sf.cindy.Message;
-import net.sf.cindy.Session;
-import net.sf.cindy.SessionAdapter;
-import net.sf.cindy.impl.ByteArrayMessage;
-
-public class SessionHandler extends SessionAdapter{
- public void sessionClosed(Session paramSession) throws Exception {
- //System.out.println("session closed");
- }
-
- public void sessionEstablished(Session paramSession) throws Exception {
- //System.out.println("session established");;
- }
-
- public void sessionIdle(Session paramSession) throws Exception {
- }
-
- public void sessionTimeout(Session paramSession) throws Exception {
- }
-
- public void messageReceived(Session session, Message message) throws Exception {
- System.out.println("message received:"+message);
- ByteArrayMessage message1 = new ByteArrayMessage();;
- message1.setContent(("received message:"+message).getBytes());
- session.write(message1);
-
- //中文乱码问题
- /* ByteBuffer bb=message.toByteBuffer()[0];
- byte[] b = new byte[bb.remaining()];
- bb.get(b, 0, b.length);
- String str=new String(b,"GBK");
- System.out.println("message received:"+str);
- ByteArrayMessage message1 = new ByteArrayMessage();;
- message1.setContent(("message received:"+str).getBytes("GBK"));
- session.write(message1);*/
-
- // ByteArrayMessage message2 = new ByteArrayMessage();
- //message2.setContent("message2" .getBytes());
- //session.blockWrite(message2);
- }
-
- public void messageSent(Session session, Message message) throws Exception {
- //System.out.println("messgae send:"+message);
- }
-
- public void exceptionCaught(Session paramSession, Throwable paramThrowable) throws Exception {
- }
-
-}
diff --git a/networkProgramming/src/eightUdpSocket/EchoClient.java b/networkProgramming/src/eightUdpSocket/EchoClient.java
deleted file mode 100644
index 9717cb0..0000000
--- a/networkProgramming/src/eightUdpSocket/EchoClient.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package eightUdpSocket;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.net.DatagramPacket;
-import java.net.DatagramSocket;
-import java.net.InetAddress;
-import java.net.SocketException;
-
-public class EchoClient {
- private String remotHost="localhost";
- private int remotPort=8000;
- private DatagramSocket socket;//发送数据报的socket
- private EchoClient() throws SocketException{
- socket=new DatagramSocket(); //与本地任意一个UDP端口绑定
- System.out.println("UDP客户端已启动...");
- }
- public void talk(){
- try {
- InetAddress remotIp=InetAddress.getByName(remotHost);
- BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
- String msg=null;
- while((msg=br.readLine())!=null){
- byte[] outputData=msg.getBytes();
- DatagramPacket outputPacket=new DatagramPacket(outputData,outputData.length,remotIp,remotPort);
- socket.send(outputPacket);//往服务端发数据报
- DatagramPacket inputPacket=new DatagramPacket(new byte[512], 512);
- socket.receive(inputPacket);//接收服务端的返回的数据报
- System.out.println(new String(inputPacket.getData(),0,inputPacket.getLength()));
- if(msg.equals("bye")){
- break;
- }
- }
- } catch (IOException e) {
- e.printStackTrace();
- }finally{
- socket.close();
- }
- }
- public static void main(String[] args) throws IOException {
- new EchoClient().talk();
- }
-
-}
diff --git a/networkProgramming/src/eightUdpSocket/EchoServer.java b/networkProgramming/src/eightUdpSocket/EchoServer.java
deleted file mode 100644
index 2ddbc54..0000000
--- a/networkProgramming/src/eightUdpSocket/EchoServer.java
+++ /dev/null
@@ -1,36 +0,0 @@
-package eightUdpSocket;
-
-import java.io.IOException;
-import java.net.DatagramPacket;
-import java.net.DatagramSocket;
-import java.net.SocketException;
-
-public class EchoServer {
- private int port=8000;
- private DatagramSocket socket;//发送数据报的socket
- private EchoServer() throws SocketException{
- socket=new DatagramSocket(port); //与本地的固UDP定端口绑定
- System.out.println("UDP服务端已启动...");
- }
- private String echo(String msg){
- return "echo:"+msg;
- }
- public void service(){
- while(true){
- try{
- DatagramPacket packet=new DatagramPacket(new byte[512], 512);//构造接收包的长度
- socket.receive(packet);//接收来自任意client的数据报
- String msg=new String(packet.getData(),0,packet.getLength());//解码并组合成msg
- System.out.println(packet.getAddress()+":"+packet.getPort()+">"+msg);//服务端输出数据
- packet.setData(echo(msg).getBytes());//字节数组类型
- socket.send(packet);//给客户端返回数据
- }catch(IOException e){
- e.printStackTrace();
- }
- }
- }
- public static void main(String[] args) throws SocketException {
- new EchoServer().service();
- }
-
-}
diff --git a/networkProgramming/src/eightUdpSocket/SpsServer.java b/networkProgramming/src/eightUdpSocket/SpsServer.java
deleted file mode 100644
index 31041f8..0000000
--- a/networkProgramming/src/eightUdpSocket/SpsServer.java
+++ /dev/null
@@ -1,152 +0,0 @@
-package eightUdpSocket;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.UnsupportedEncodingException;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.UnknownHostException;
-
-//此线程类 用于处理接收到连接状态的 客户端的收发处理
-//若多个客户端连接则会创建多个实例
-class ServerThread extends Thread {
-
- private Socket m_Client = null;
- private InputStream in = null;
- private OutputStream out = null;
- private BizCommonService bizCommonService;
- private String ENCODING = "GBK";
-
- public ServerThread(Socket _client,BizCommonService bizCommonService) throws Exception {
- this.m_Client = _client;
- this.in = m_Client.getInputStream(); // 获取出入流
- this.out = m_Client.getOutputStream();// 获取输出流
- this.bizCommonService=bizCommonService;
- }
-
- public void run() {
- byte[] recvBuf = new byte[2048];
- byte[] sendBuf = new byte[2048];
- int len = 0;
-
- while (true) {
- // 先判断客户端连接状态
- try {
- m_Client.sendUrgentData(0);
- } catch (IOException e) {
- break;// 失去连接
- }
-
- // 输入流从网络上读取数据
- try {
- len = in.read(recvBuf);
- System.out.println("len:"+len);
- if(len==-1){
- //没收到数据断开连接
- break;
- }else{
- System.out.println("recv:" + new String(recvBuf, 0, len,ENCODING));
- }
- } catch (IOException e) {
- break;// 接收异常
- }
- //收到的数据
- String recv="";
- try {
- recv = new String(recvBuf, 0, len,ENCODING);
- } catch (UnsupportedEncodingException e1) {
- e1.printStackTrace();
- }
- boolean result = bizCommonService.sendOperToCacheAysn(recv);
- /**
- * step 3 : 创建响应报文
- */
- String res = bizCommonService.createResponseStr(recv,result);
- sendBuf = res.getBytes();
- try {
- out.write(sendBuf);
- System.out.println("send:" + res);
- } catch (IOException e) {
- break;// 发送异常
- }
- }
-
- System.out.println("客户端失去连接");
- try {
- in.close();
- out.close();
- m_Client.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-}
-
-// 此线程类用于接收服务端socket监听到的客户端连接 并创建线程对于此客户端的处理
-class ClientRequestProc extends Thread {
-
- private ServerSocket m_Server = null;
- private BizCommonService bizCommonService;
-
- public ClientRequestProc(ServerSocket _server,BizCommonService bizCommonService) {
- m_Server = _server;
- this. bizCommonService=bizCommonService;
- }
-
- public void run() {
- while (true) {
- try {
- Socket client = m_Server.accept();
- System.out.println("有客户端连接");
- try {
- ServerThread proc = new ServerThread(client,bizCommonService);
- proc.start();
- } catch (Exception e) {
- e.printStackTrace();
- }
- System.out.println("启动客户端处理线程");
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
-}
-
-public class SpsServer {
- public static void main(String[] args) {
- final Logger log = LoggerFactory.getLogger(SpsServer.class);
- try{
- ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
- new String[] { "applicationContext.xml" });
- context.start();
- BizCommonService bizCommonService = (BizCommonService) context.getBean("bizCommonService");
- SpsServer.serverStart(bizCommonService);
- }catch(Exception e){
- log.error("start sps interface server error:",e);
- System.exit(-1);
- }
- }
- public static void serverStart(BizCommonService bizCommonService){
- ServerSocket server = null;
- int PORT=10002;
- //int PORT=30087;//prod
- //String PORTs=(String)CustomizedPropertyConfigurer.getContextProperty("toSpsServerPort");
- //PORT=Integer.parseInt(PORTs);
- try {
- server = new ServerSocket(PORT);
- } catch (IOException e) {
- e.printStackTrace();
- }
- String ip=server.getInetAddress().getHostAddress();
- System.out.println(ip+":"+PORT+"服务器开始监听...\n");
- ClientRequestProc clientRp = new ClientRequestProc(server,bizCommonService);
- clientRp.start();
- try {
- clientRp.join();// 等待子线程退出(阻塞函数 防止主线程先结束)
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
-}
\ No newline at end of file
diff --git a/networkProgramming/src/eightUdpSocket/package-info.java b/networkProgramming/src/eightUdpSocket/package-info.java
deleted file mode 100644
index 8b58bb0..0000000
--- a/networkProgramming/src/eightUdpSocket/package-info.java
+++ /dev/null
@@ -1,8 +0,0 @@
-/**
- *
- */
-/**
- * @author mercy
- *基于UDP的数据报和套接字
- */
-package eightUdpSocket;
\ No newline at end of file
diff --git a/networkProgramming/src/fourNoBlocking/Handler.java b/networkProgramming/src/fourNoBlocking/Handler.java
deleted file mode 100644
index 46c0077..0000000
--- a/networkProgramming/src/fourNoBlocking/Handler.java
+++ /dev/null
@@ -1,56 +0,0 @@
-package fourNoBlocking;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.net.Socket;
-import java.nio.channels.SocketChannel;
-
-public class Handler implements Runnable{
- private SocketChannel socketChannel;
- public Handler(SocketChannel socketChannel){
- this.socketChannel=socketChannel;
- }
- public String echo(String msg){
- return "echo:"+msg;
- }
- private PrintWriter getWriter(Socket socket) throws IOException{
- OutputStream socketOut=socket.getOutputStream();
- return new PrintWriter(socketOut,true);
- }
- private BufferedReader getReader(Socket socket)throws IOException{
- InputStream socketIn=socket.getInputStream();
- return new BufferedReader(new InputStreamReader(socketIn));
- }
- @Override
- public void run() {
- handle(socketChannel);
- }
- public void handle(SocketChannel socketChannel){
- Socket socket=socketChannel.socket();//获取socket对象
- System.out.println("服务端执行线程..绑定的客户端port:"+socket.getPort());
- try{
- BufferedReader br=getReader(socket);
- PrintWriter pw=getWriter(socket);
- String msg=null;
- while((msg=br.readLine())!=null){
- System.out.println(msg);
- pw.println(echo(msg));
- }
- }catch(IOException e){
- e.printStackTrace();
- }finally{
- if(socket!=null){
- try {
- socket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
-
-}
diff --git a/networkProgramming/src/fourNoBlocking/NIOBlockEchoClient.java b/networkProgramming/src/fourNoBlocking/NIOBlockEchoClient.java
deleted file mode 100644
index 5c29ba3..0000000
--- a/networkProgramming/src/fourNoBlocking/NIOBlockEchoClient.java
+++ /dev/null
@@ -1,67 +0,0 @@
-package fourNoBlocking;
-
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.nio.channels.SocketChannel;
-
-
-/**
- * @author mercy
- * 阻塞式NIO客户端
- */
-public class NIOBlockEchoClient {
- private SocketChannel socketChannel=null;
- private int port=10002;
- public NIOBlockEchoClient()throws IOException{
- socketChannel=SocketChannel.open();
- InetAddress ad=InetAddress.getLocalHost();
- InetSocketAddress isa=new InetSocketAddress(ad,port);
- socketChannel.connect(isa);//连接服务
- //获取绑定后的端口号和绑定前的端口号
- }
-
- private PrintWriter getWriter(Socket socket) throws IOException{
- OutputStream socketOut=socket.getOutputStream();
- return new PrintWriter(socketOut,true);
- }
- private BufferedReader getReader(Socket socket)throws IOException{
- InputStream socketIn=socket.getInputStream();
- return new BufferedReader(new InputStreamReader(socketIn));
- }
-
- public void talk() throws IOException{
- try{
- BufferedReader br=getReader(socketChannel.socket());
- PrintWriter pw=getWriter(socketChannel.socket());
- BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
- String msg=null;
- while((msg=reader.readLine())!=null){
- pw.println(msg);
- System.out.println(br.readLine());
- if(msg.equals("bye")){
- break;
- }
- }
- }catch(IOException e){
- e.printStackTrace();
- }
- try{
- socketChannel.close();
- }catch(IOException e){
- e.printStackTrace();
- }
- }
- public static void main(String[] args) throws IOException{
- new NIOBlockEchoClient().talk();
- }
-
-
-}
diff --git a/networkProgramming/src/fourNoBlocking/NIOBlockEchoServer.java b/networkProgramming/src/fourNoBlocking/NIOBlockEchoServer.java
deleted file mode 100644
index 19f186f..0000000
--- a/networkProgramming/src/fourNoBlocking/NIOBlockEchoServer.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package fourNoBlocking;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.nio.channels.ServerSocketChannel;
-import java.nio.channels.SocketChannel;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-
-
-/**
- * @author mercy
- * 用nio创建阻塞式IO服务端(当ServerSocketChannel和SocketChannel采用阻塞式IO时为了处理多个连接必须使用多线程)
- */
-public class NIOBlockEchoServer {
- private int port=8000;
- private ServerSocketChannel serverSocketChannel;
- private ExecutorService servicePool;//线程池
- private final int poolSize=5;
- public NIOBlockEchoServer() throws IOException{
- //返回当前电脑系统的CPU数目,CPU越多,线程池工作的数目也越多
- servicePool=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*poolSize);
- //创建对象
- serverSocketChannel=ServerSocketChannel.open();
- //设置在同一主机上关闭服务器端程序再启动该程序时候可以顺利绑定相同端口
- serverSocketChannel.socket().setReuseAddress(true);
- //使得服务器进程与本地端口绑定
- serverSocketChannel.socket().bind(new InetSocketAddress(port));
- System.out.println("服务已启动...");
- }
- public void service(){
- while(true){
- SocketChannel socketChannel=null;
- try{
- socketChannel=serverSocketChannel.accept();
- servicePool.execute(new Handler(socketChannel));//创建一个工作线程
- }catch(IOException e){
- e.printStackTrace();
- }
-
- }
- }
- public static void main(String[] args) throws IOException {
- new NIOBlockEchoServer().service();
- }
-
-}
diff --git a/networkProgramming/src/fourNoBlocking/NoBlockAndBlockServer.java b/networkProgramming/src/fourNoBlocking/NoBlockAndBlockServer.java
deleted file mode 100644
index 0e1e205..0000000
--- a/networkProgramming/src/fourNoBlocking/NoBlockAndBlockServer.java
+++ /dev/null
@@ -1,147 +0,0 @@
-package fourNoBlocking;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.ServerSocketChannel;
-import java.nio.channels.SocketChannel;
-import java.nio.charset.Charset;
-import java.util.Iterator;
-import java.util.Set;
-
-/**
- * @author mercy
- * 接收客户连接按照阻塞模式,有就注册读就绪和写就绪事件,否则进入阻塞模式,直到接收到了客户连接负责接收数据和发送数据的线程采用非阻塞模式
- * 单独出一个accept方法
- *
- */
-public class NoBlockAndBlockServer {
- private Selector selector=null;
- private ServerSocketChannel serverSocketChannel=null;
- private int port=8000;
- private Charset charset=Charset.forName("GBK");//返回一个字符类型对象
-
- public NoBlockAndBlockServer() throws IOException{
- selector=Selector.open();//创建Selector对象
- serverSocketChannel=ServerSocketChannel.open();
- serverSocketChannel.socket().setReuseAddress(true);
- serverSocketChannel.socket().bind(new InetSocketAddress(port));
- System.out.println("服务已启动...");
- }
- private Object gate=new Object();
- public void accept(){
- for(;;){
- try{
- SocketChannel socketChannel=serverSocketChannel.accept();
- socketChannel.configureBlocking(false);//设置无阻塞模式
- ByteBuffer buffer=ByteBuffer.allocate(6555);//创建一个ByteBuffer对象用于存放数据
- synchronized (gate) {
- selector.wakeup();//唤醒阻塞在select方法上的线程
- socketChannel.register(selector,SelectionKey.OP_READ|SelectionKey.OP_WRITE,buffer);
- }
- }catch(IOException e){
- e.printStackTrace();
- }
- }
-
- }
- public void service() throws IOException{
- for(;;){
- synchronized (gate) {}
- int n=selector.select();//已经可以进行IO的通道数
- if(n==0){
- continue;
- }
- Set readyKeys=selector.selectedKeys();
- Iterator it=readyKeys.iterator();
- while(it.hasNext()){
- SelectionKey key=null;
- key=(SelectionKey)it.next();
- it.remove();//删除集合中的key
- try{
- if(key.isReadable()){//key的channel是否可读
- receive(key);
- }
- if(key.isWritable()){//key的channel是否可写
- send(key);
- }
- }catch(IOException e){
- e.printStackTrace();
- try{
- if(key!=null){
- key.cancel();
- key.channel().close();
- }
- }catch(Exception ex){
- ex.printStackTrace();
- }
- }
- }
- }
- }
- /**
- * @param key
- * @throws IOException
- * @author mercy
- * 根据读取的数据处理完返回给客户端
- */
- public void send(SelectionKey key) throws IOException{
- ByteBuffer buffer=(ByteBuffer) key.attachment();//检索当前的文件
- SocketChannel socketChannel=(SocketChannel) key.channel();
- buffer.flip();//把极限(limit)设为位置(position),把位置设为0
- String data=decode(buffer);//解码客户端发过来的数据
- if(data.indexOf("\r\n")==-1){//不包含\r\n直接return
- return ;
- }
- String outputData=data.substring(0, data.indexOf("\n")+1);
- System.out.println("客户端发送的数据:"+outputData);
- ByteBuffer outputBuffer=encode("echo:"+outputData);//返回给客户端的数据
- while(outputBuffer.hasRemaining()){//buffer里面有数据
- socketChannel.write(outputBuffer);
- }
- ByteBuffer temp=encode(outputData);
- buffer.position(temp.limit());//设置buffer的位置为temp的极限
- buffer.compact();//删除已经处理的字符串
- if(outputData.equals("bye\r\n")){
- key.cancel();
- socketChannel.close();
- System.out.println("关闭与某客户端的连接");
- }
- }
- /**
- * @param key
- * @throws IOException
- * @author mercy
- * 读取客户端发来的数据
- */
- public void receive(SelectionKey key) throws IOException{
- ByteBuffer buffer=(ByteBuffer) key.attachment();
- SocketChannel socketChannel=(SocketChannel) key.channel();
- ByteBuffer readBuffer=ByteBuffer.allocate(6555);//创建自定义内存的buffer
- socketChannel.read(readBuffer);
- readBuffer.flip();
- buffer.limit(buffer.capacity());//设置buffer的极限为buffer的容量
- buffer.put(readBuffer);
- }
- public String decode(ByteBuffer buffer){//解码
- CharBuffer charBuffer=charset.decode(buffer);
- return charBuffer.toString();
-
- }
- public ByteBuffer encode(String str){//编码
- return charset.encode(str);
- }
- public static void main(String[] args) throws IOException {
- final NoBlockAndBlockServer server=new NoBlockAndBlockServer();
- Thread accept= new Thread(){
- public void run(){
- server.accept();
- }
- };
- accept.start();
- server.service();
- }
-}
diff --git a/networkProgramming/src/fourNoBlocking/NoBlockClient.java b/networkProgramming/src/fourNoBlocking/NoBlockClient.java
deleted file mode 100644
index 4b0e5a4..0000000
--- a/networkProgramming/src/fourNoBlocking/NoBlockClient.java
+++ /dev/null
@@ -1,151 +0,0 @@
-package fourNoBlocking;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.SocketChannel;
-import java.nio.charset.Charset;
-import java.util.Iterator;
-import java.util.Set;
-
-/**
- * @author mercy
- * 非阻塞式IO客户端
- */
-public class NoBlockClient {
- private SocketChannel socketChannel=null;
- private ByteBuffer sendBuffer=ByteBuffer.allocate(1024);
- private ByteBuffer receiveBuffer=ByteBuffer.allocate(1024);
- private Charset charset=Charset.forName("GBK");
- private Selector selector;
- private int port=8000;
- public NoBlockClient() throws IOException{
- socketChannel=SocketChannel.open();
- InetAddress add=InetAddress.getLocalHost();
- InetSocketAddress isa=new InetSocketAddress(add, port);
- socketChannel.connect(isa);//采用阻塞模式连接服务器
- socketChannel.configureBlocking(false);//采用非阻塞模式
- System.out.println("连接服务器成功....");
- selector=Selector.open();
- }
- /**
- *
- * @author mercy
- * 接收用户从控制台输入的数据
- */
- public void receiveFromUser(){
- try{
- //用户输入的数据放入buffer中
- BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
- String msg=null;
- while((msg=br.readLine())!=null){
- synchronized (sendBuffer) {
- sendBuffer.put(encode(msg+"\r\n"));
- }
- if(msg.equals("bye")){
- break;
- }
- }
- }catch(IOException e){
- e.printStackTrace();
- }
- }
-
- /**
- * @param key
- * @author mercy
- * 发送sendBuffer中的数据
- * @throws IOException
- */
- public void send(SelectionKey key) throws IOException{
- SocketChannel socketChannel=(SocketChannel) key.channel();
- synchronized (sendBuffer) {
- sendBuffer.flip();//将极限(limit)设为位置(position),将位置设为0
- socketChannel.write(sendBuffer);
- sendBuffer.compact();//删除已经发送的数据
- }
- }
- /**
- * @param key
- * @throws IOException
- * @author mercy
- * 接收服务端发送的数据,如果buffer中有数据则打印,然后从buffer中删除
- */
- public void receive(SelectionKey key) throws IOException{
- SocketChannel socketChannel=(SocketChannel) key.channel();
- socketChannel.read(receiveBuffer);
- receiveBuffer.flip();
- String receiveData=decode(receiveBuffer);
- if(receiveData.indexOf("\n")==-1){
- return;
- }
- String outputData=receiveData.substring(0, receiveData.indexOf("\n")+1);
- System.out.println(outputData);
- if(outputData.equals("echo:bye\r\n")){
- key.cancel();
- socketChannel.close();
- System.out.println("连接服务器关闭...");
- selector.close();
- System.exit(0);
- }
- ByteBuffer temp=encode(outputData);
- receiveBuffer.position(temp.limit());
- receiveBuffer.compact();//删除已经打印的数据
- }
-
- public String decode(ByteBuffer buffer){//解码
- CharBuffer charBuffer=charset.decode(buffer);
- return charBuffer.toString();
-
- }
- public ByteBuffer encode(String str){//编码
- return charset.encode(str);
- }
- public void talk()throws IOException{
- socketChannel.register(selector,SelectionKey.OP_READ|SelectionKey.OP_WRITE);
- while(selector.select()>0){
- Set readyKeys=selector.selectedKeys();
- Iterator it=readyKeys.iterator();
- while(it.hasNext()){
- SelectionKey key=null;
- try{
- key=(SelectionKey) it.next();
- it.remove();
- if(key.isReadable()){
- receive(key);
- }
- if(key.isWritable()){
- send(key);
- }
- }catch(IOException e){
- e.printStackTrace();
- try{
- if(key!=null){
- key.cancel();
- key.channel().close();
- }
- }catch(Exception ex){
- e.printStackTrace();
- }
- }
- }
- }
- }
- public static void main(String[] args) throws IOException {
- final NoBlockClient client=new NoBlockClient();
- Thread receiver=new Thread(){
- public void run(){
- client.receiveFromUser();//接收用户输入的数据
- }
- };
- receiver.start();
- client.talk();
- }
-
-}
diff --git a/networkProgramming/src/fourNoBlocking/NoBlockServer.java b/networkProgramming/src/fourNoBlocking/NoBlockServer.java
deleted file mode 100644
index 02f7fba..0000000
--- a/networkProgramming/src/fourNoBlocking/NoBlockServer.java
+++ /dev/null
@@ -1,137 +0,0 @@
-package fourNoBlocking;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.channels.SelectionKey;
-import java.nio.channels.Selector;
-import java.nio.channels.ServerSocketChannel;
-import java.nio.channels.SocketChannel;
-import java.nio.charset.Charset;
-import java.util.Iterator;
-import java.util.Set;
-
-/**
- * @author mercy
- * NIO创建非阻塞式服务端
- * 一个主线程能接收客户的连接,接收客户的请求,向客户发回响应数据
- * ByteBuffer是字节缓存区,存放的是字节,要转换成字符串需要编解码
- */
-public class NoBlockServer {
- private Selector selector=null;
- private ServerSocketChannel serverSocketChannel=null;
- private int port=8000;
- private Charset charset=Charset.forName("GBK");//返回一个字符类型对象
-
- public NoBlockServer() throws IOException{
- selector=Selector.open();//创建Selector对象
- serverSocketChannel=ServerSocketChannel.open();
- serverSocketChannel.socket().setReuseAddress(true);
- serverSocketChannel.configureBlocking(false);//设置无阻塞模式
- serverSocketChannel.socket().bind(new InetSocketAddress(port));
- System.out.println("服务已启动...");
- }
-
- public void service() throws IOException{
- serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);//用给定的选择器注册channel,并返回一个key
- while(selector.select()>0){
- Set readyKeys=selector.selectedKeys();
- Iterator it=readyKeys.iterator();
- while(it.hasNext()){
- SelectionKey key=null;
- try{
- key=(SelectionKey)it.next();
- it.remove();//删除集合中的key
- if(key.isAcceptable()){//是否可以接收客户端的socket连接
- ServerSocketChannel ssc=(ServerSocketChannel)key.channel();
- SocketChannel socketChannel=ssc.accept();
- System.out.println("接收到的客户端连接,来自:"+socketChannel.socket().getInetAddress()+":"+socketChannel.socket().getPort());
- socketChannel.configureBlocking(false);//设置无阻塞模式
- ByteBuffer buffer=ByteBuffer.allocate(2048);//创建一个ByteBuffer对象用于存放数据(数据存放缓冲区)
- socketChannel.register(selector,SelectionKey.OP_READ|SelectionKey.OP_WRITE,buffer);//注册事件,Selector会监控事件是否发生
- }
- if(key.isReadable()){//key的channel是否可读
- receive(key);
- }
- if(key.isWritable()){//key的channel是否可写
- send(key);
- }
- }catch(IOException e){
- System.out.println("exception....");
- e.printStackTrace();
- try{
- if(key!=null){
- key.cancel();
- key.channel().close();
- }
- }catch(Exception ex){
- ex.printStackTrace();
- }
- }
- }
- }
-
- }
- /**
- * @param key
- * @throws IOException
- * @author mercy
- * 根据读取的数据处理完返回给客户端
- */
- public void send(SelectionKey key) throws IOException{
- ByteBuffer buffer=(ByteBuffer) key.attachment();//检索当前的文件
- SocketChannel socketChannel=(SocketChannel) key.channel();
- buffer.flip();//把极限(limit)设为位置(position),把位置设为0
- String data=decode(buffer);//解码客户端发过来的数据
- if(data.length()==0){
- return ;
- }
-// if(data.indexOf("\r\n")==-1){//不包含\r\n直接return
-// return ;
-// }
- String outputData=data;//.substring(0, data.indexOf("\n")+1);
- System.out.println("客户端发送的数据:"+outputData);
- ByteBuffer outputBuffer=encode("echo:"+outputData);//返回给客户端的数据
- while(outputBuffer.hasRemaining()){//buffer里面有数据
- socketChannel.write(outputBuffer);
- }
- ByteBuffer temp=encode(outputData);
- buffer.position(temp.limit());//设置buffer的位置:temp的极限
- buffer.compact();//删除已经处理的字符串(删除缓冲区内从0到当前位置position的内容)
- if(outputData.equals("bye\r\n")){
- key.cancel();
- socketChannel.close();
- System.out.println("关闭与某客户端的连接");
- }
- }
- /**
- * @param key
- * @throws IOException
- * @author mercy
- * 读取客户端发来的数据
- */
- public void receive(SelectionKey key) throws IOException{
- ByteBuffer buffer=(ByteBuffer) key.attachment();
-// if(!buffer.hasRemaining()){
-// return ;
-// }
- SocketChannel socketChannel=(SocketChannel) key.channel();
- ByteBuffer readBuffer=ByteBuffer.allocate(2048);//创建自定义内存的buffer(存放读到的数据)
- socketChannel.read(readBuffer);
- readBuffer.flip();
- buffer.limit(buffer.capacity());//设置buffer的极限为buffer的容量
- buffer.put(readBuffer);//复制到缓存区
- }
- public String decode(ByteBuffer buffer){//解码
- CharBuffer charBuffer=charset.decode(buffer);
- return charBuffer.toString();
-
- }
- public ByteBuffer encode(String str){//编码
- return charset.encode(str);
- }
- public static void main(String[] args) throws IOException {
- new NoBlockServer().service();
- }
-}
diff --git a/networkProgramming/src/fourNoBlocking/SendClient.java b/networkProgramming/src/fourNoBlocking/SendClient.java
deleted file mode 100644
index e6dee81..0000000
--- a/networkProgramming/src/fourNoBlocking/SendClient.java
+++ /dev/null
@@ -1,109 +0,0 @@
-package fourNoBlocking;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.nio.ByteBuffer;
-
-
-/**
- *
- * 发送报文给客户端
- *
- *
- * @author zhouzhixiang
- * @date 2016年12月14日 上午11:56:27
- * @since 1.0
- */
-public class SendClient {
-
- private static final String ENCODING = "GBK";
-
- public static String send(String ip, int port, String sendStr, int timeout) {
- long start = System.currentTimeMillis();
- System.out.println(sendStr.length());
- if (sendStr == null || "".equals(sendStr)) {
- return "str is null";
- }
- Socket client = null;
- OutputStream stream = null;
- InputStream is = null;
-
- try {
- client = new Socket();
- InetSocketAddress address = new InetSocketAddress(ip, port);
- client.connect(address);
-
- timeout = timeout >= 0 ? timeout : 3500;
- client.setSoTimeout(timeout);
- stream = client.getOutputStream();
- is = client.getInputStream();
-
- int len = 0;
-
- len = sendStr.getBytes(ENCODING).length;
- ByteBuffer buf = ByteBuffer.allocate(len);
- byte[] bytes = sendStr.getBytes(ENCODING);
- buf.put(bytes);
- stream.write(buf.array(), 0, len);
- stream.flush();
- String res = "";
- int i = 0;
- byte[] b = new byte[6555];
- while ((i = is.read(b)) != -1) {
- res = new String(b, 0, i);
- System.out.println(res);
- break;
- }
- long end = System.currentTimeMillis();
-
-
- return res;
- } catch (Exception e) {
- StringBuilder strBuilder = new StringBuilder();
- strBuilder.append("error send message").append(e.getMessage()).append("&errorID=")
- .append(System.currentTimeMillis());
- return strBuilder.toString();
- } finally {
- if (client != null) {
- try {
- client.close();
- } catch (IOException e) {
- StringBuilder strBuilder = new StringBuilder();
- strBuilder.append("error send message").append(e.getMessage()).append("&errorID=")
- .append(System.currentTimeMillis());
- }
- }
-
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException e) {
- StringBuilder strBuilder = new StringBuilder();
- strBuilder.append("error send message").append(e.getMessage()).append("&errorID=")
- .append(System.currentTimeMillis());
- }
- }
- if (is != null) {
- try {
- is.close();
- } catch (IOException e) {
- StringBuilder strBuilder = new StringBuilder();
- strBuilder.append("error send message").append(e.getMessage()).append("&errorID=")
- .append(System.currentTimeMillis());
- }
- }
- }
- }
-
- public static void main(String[] args) {
- String msg="";
- msg="FFFF76623634010100102700170103IBSS017555 000000021800100023402287248808*766236340100200001178400003001785000030217860000302110000004075510100020SZ2000000054121442461020001241324186148310300593PM_DJDHHM||83456517||001#$PM_HYLX||0||001#$BA_MSMAN||海豚||001#$PM_DJQYYB||518000||001#$PM_DJQYMC||深圳市福田区人力资源服务中心||001#$PM_BHHM||83456517||001#$PM_DJQYDZ||福田区福强路深圳文化创意园世纪工艺品文化广场309栋B座1-3层||001#$PM_SFZDXY||XY02||001#$PM_DJKHXX||||001#$BA_MSDEPTNAME||12||001#$PM_DLS||DSL6||001#$PM_YWSLLB||SLLB01||001#$PM_SLDYSLSH||0||001#$PM_JFQ||01||001#$PM_DJHMGS||1||001#$PM_SRFJ||2||001#$PM_JFJG||1||001#$PM_YZ||30||001#$PM_DXFSSL||100||001#$PB_BILLINGTYPE||000000||005#$PB_USERTYPE||100002||005#$PB_USERCHAR||JFSX01||005#$BEGIN_DATE||20170607||005#$END_DATE||||005#$10400014DXMP214688722910700016号百信息服务中心10800010122810070411400006徐冬生115000088291816511600110114+企业名片行业版包月套餐,114+短信名片包月套餐_定价计划,114+企业名片行业版包月套餐赠送3个月套餐外等额话费优惠11700017755KH000293285120";
- //String x=SendClient.send("weway.wicp.net", 10101, msg, 3500);
- String x=SendClient.send("127.0.0.1", 8000, msg, 3500);
- System.out.println("return string:"+x);
- }
-
-}
diff --git a/networkProgramming/src/fourNoBlocking/package-info.java b/networkProgramming/src/fourNoBlocking/package-info.java
deleted file mode 100644
index 9b0029f..0000000
--- a/networkProgramming/src/fourNoBlocking/package-info.java
+++ /dev/null
@@ -1,9 +0,0 @@
-/**
- *
- */
-/**
- * @author mercy
- * 使用非阻塞式IO创建服务端程序和客户端程序
- */
-package fourNoBlocking;
-
diff --git a/networkProgramming/src/framework/grizzly/EchoClient.java b/networkProgramming/src/framework/grizzly/EchoClient.java
deleted file mode 100644
index 13f84b3..0000000
--- a/networkProgramming/src/framework/grizzly/EchoClient.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package framework.grizzly;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.net.Socket;
-
-public class EchoClient {
- private String host="localhost";
- private int port=10003;
- private Socket socket;
- public EchoClient()throws IOException{
- socket=new Socket(host,port);
- //获取绑定后的端口号和绑定前的端口号
- System.out.println("new Connecttion accept" +socket.getInetAddress()+":"+socket.getPort()+",localPort:"+socket.getLocalPort());
- }
- private PrintWriter getWriter(Socket socket) throws IOException{
- OutputStream socketOut=socket.getOutputStream();
- return new PrintWriter(socketOut,true);
- }
- private BufferedReader getReader(Socket socket)throws IOException{
- InputStream socketIn=socket.getInputStream();
- return new BufferedReader(new InputStreamReader(socketIn));
- }
- public void talk() throws IOException{
- try{
- BufferedReader br=getReader(socket);
- PrintWriter pw=getWriter(socket);
- BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
- String msg=null;
- while((msg=reader.readLine())!=null){
- pw.println(msg);
- System.out.println(br.readLine());
- if(msg.equals("bye")){
- break;
- }
- }
- }catch(IOException e){
- e.printStackTrace();
- }
- try{
- socket.close();
- }catch(IOException e){
- e.printStackTrace();
- }
- }
- public static void main(String[] args) throws IOException{
- new EchoClient().talk();
- }
-
-}
diff --git a/networkProgramming/src/framework/grizzly/GrizzlyEchoClient.java b/networkProgramming/src/framework/grizzly/GrizzlyEchoClient.java
deleted file mode 100644
index 5e4b9ce..0000000
--- a/networkProgramming/src/framework/grizzly/GrizzlyEchoClient.java
+++ /dev/null
@@ -1,75 +0,0 @@
-package framework.grizzly;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.nio.charset.Charset;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-
-import org.glassfish.grizzly.Connection;
-import org.glassfish.grizzly.filterchain.FilterChainBuilder;
-import org.glassfish.grizzly.filterchain.TransportFilter;
-import org.glassfish.grizzly.nio.transport.TCPNIOTransport;
-import org.glassfish.grizzly.nio.transport.TCPNIOTransportBuilder;
-import org.glassfish.grizzly.utils.Charsets;
-import org.glassfish.grizzly.utils.StringFilter;
-
-public class GrizzlyEchoClient {
-
- @SuppressWarnings("unchecked")
- public static void main(String[] args) throws IOException,
- ExecutionException, InterruptedException, TimeoutException {
-
- Connection connection = null;
-
- // Create a FilterChain using FilterChainBuilder
- FilterChainBuilder filterChainBuilder = FilterChainBuilder.stateless();
- // Add TransportFilter, which is responsible
- // for reading and writing data to the connection
- filterChainBuilder.add(new TransportFilter());
- // StringFilter is responsible for Buffer <-> String conversion
- filterChainBuilder.add(new StringFilter(Charset.forName("GBK")));
- // ClientFilter is responsible for redirecting server responses to the standard output
- filterChainBuilder.add(new GrizzlyEchoClientFilter());
-
- // Create TCP transport
- final TCPNIOTransport transport =
- TCPNIOTransportBuilder.newInstance().build();
- transport.setProcessor(filterChainBuilder.build());
-
- try {
- // start the transport
- transport.start();
-
- // perform async. connect to the server
- Future future = transport.connect("127.0.0.1",
- GrizzlyEchoServer.PORT);
- // wait for connect operation to complete
- connection = future.get(10, TimeUnit.SECONDS);
-
- assert connection != null;
-
- System.out.println("Ready... (\"q\" to exit)");
- final BufferedReader inReader = new BufferedReader(
- new InputStreamReader(System.in, Charsets.ASCII_CHARSET));
- do {
- final String userInput = inReader.readLine();
- if (userInput == null || "q".equals(userInput)) {
- break;
- }
-
- connection.write(userInput);
- } while (true);
- } finally {
- // close the client connection
- if (connection != null) {
- connection.closeSilently();
- }
- // stop the transport
- transport.shutdownNow();
- }
- }
-}
diff --git a/networkProgramming/src/framework/grizzly/GrizzlyEchoClientFilter.java b/networkProgramming/src/framework/grizzly/GrizzlyEchoClientFilter.java
deleted file mode 100644
index 944d0b1..0000000
--- a/networkProgramming/src/framework/grizzly/GrizzlyEchoClientFilter.java
+++ /dev/null
@@ -1,26 +0,0 @@
-package framework.grizzly;
-
-import java.io.IOException;
-
-import org.glassfish.grizzly.filterchain.BaseFilter;
-import org.glassfish.grizzly.filterchain.FilterChainContext;
-import org.glassfish.grizzly.filterchain.NextAction;
-
-public class GrizzlyEchoClientFilter extends BaseFilter {
- /**
- * Handle just read operation, when some message has come and ready to be
- * processed.
- *
- * @param ctx Context of {@link FilterChainContext} processing
- * @return the next action
- * @throws java.io.IOException
- */
- @Override
- public NextAction handleRead(final FilterChainContext ctx) throws IOException {
- // We get String message from the context, because we rely prev. Filter in chain is StringFilter
- final String serverResponse = ctx.getMessage();
- System.out.println("Server echo: " + serverResponse);
-
- return ctx.getStopAction();
- }
-}
diff --git a/networkProgramming/src/framework/grizzly/GrizzlyEchoFilter.java b/networkProgramming/src/framework/grizzly/GrizzlyEchoFilter.java
deleted file mode 100644
index 2e951f5..0000000
--- a/networkProgramming/src/framework/grizzly/GrizzlyEchoFilter.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package framework.grizzly;
-
-import java.io.IOException;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import org.glassfish.grizzly.Buffer;
-import org.glassfish.grizzly.Connection;
-import org.glassfish.grizzly.Grizzly;
-import org.glassfish.grizzly.filterchain.BaseFilter;
-import org.glassfish.grizzly.filterchain.FilterChainContext;
-import org.glassfish.grizzly.filterchain.NextAction;
-
-public class GrizzlyEchoFilter extends BaseFilter{
- private static final Logger logger = Grizzly.logger(GrizzlyEchoFilter.class);
- public NextAction handleRead(FilterChainContext ctx) throws IOException{
- Object message = ctx.getMessage();
- Connection connection = ctx.getConnection();
- Object address = ctx.getAddress();
- if (logger.isLoggable(Level.FINEST)) {
- logger.log(Level.FINEST, "EchoFilter. connection={0} dstAddress={1} message={2}",
- new Object[] { connection, address, message });
- }
- if (message instanceof Buffer) {
- ((Buffer) message).allowBufferDispose(true);
- }
- System.out.println("message:"+message);
- ctx.write(address, message, null);
- return ctx.getStopAction();
- }
-}
\ No newline at end of file
diff --git a/networkProgramming/src/framework/grizzly/GrizzlyEchoServer.java b/networkProgramming/src/framework/grizzly/GrizzlyEchoServer.java
deleted file mode 100644
index 1d8675d..0000000
--- a/networkProgramming/src/framework/grizzly/GrizzlyEchoServer.java
+++ /dev/null
@@ -1,59 +0,0 @@
-package framework.grizzly;
-import java.io.IOException;
-import java.nio.charset.Charset;
-import java.util.logging.Logger;
-import org.glassfish.grizzly.filterchain.FilterChainBuilder;
-import org.glassfish.grizzly.filterchain.TransportFilter;
-import org.glassfish.grizzly.nio.transport.TCPNIOTransport;
-import org.glassfish.grizzly.nio.transport.TCPNIOTransportBuilder;
-import org.glassfish.grizzly.utils.StringFilter;
-
-/**
- * Class initializes and starts the echo server, based on Grizzly 2.0
- *
- * @author Alexey Stashok
- */
-public class GrizzlyEchoServer {
- private static final Logger logger = Logger.getLogger(GrizzlyEchoServer.class.getName());
- public static final String ADDR="127.0.0.1";
- public static final int PORT = 10003;
-
- public static void main(String[] args) throws IOException {
- // Create a FilterChain using FilterChainBuilder
- FilterChainBuilder filterChainBuilder = FilterChainBuilder.stateless();
-
- // Add TransportFilter, which is responsible
- // for reading and writing data to the connection
- filterChainBuilder.add(new TransportFilter());
-
- // StringFilter is responsible for Buffer <-> String conversion
- filterChainBuilder.add(new StringFilter(Charset.forName("GBK")));
-
- // EchoFilter is responsible for echoing received messages
- filterChainBuilder.add(new GrizzlyEchoFilter());
-
- // Create TCP transport
- final TCPNIOTransport transport =
- TCPNIOTransportBuilder.newInstance().build();
-
- transport.setProcessor(filterChainBuilder.build());
-
- try {
- // binding transport to start listen on certain host and port
- logger.info("binding transport to start listen on certain host and port");
- transport.bind(ADDR,PORT);
-
- // start the transport
- transport.start();
-
- //logger.info("Press any key to stop the server...");
- System.in.read();
- } finally {
- //logger.info("Stopping transport...");
- // stop the transport
- transport.shutdownNow();
-
- logger.info("Stopped transport...");
- }
- }
-}
\ No newline at end of file
diff --git a/networkProgramming/src/framework/grizzly/GrizzlyEchoServer1.java b/networkProgramming/src/framework/grizzly/GrizzlyEchoServer1.java
deleted file mode 100644
index 7c7a9d9..0000000
--- a/networkProgramming/src/framework/grizzly/GrizzlyEchoServer1.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package framework.grizzly;
-import java.io.IOException;
-import java.nio.charset.Charset;
-import java.util.logging.Logger;
-import org.glassfish.grizzly.filterchain.FilterChainBuilder;
-import org.glassfish.grizzly.filterchain.TransportFilter;
-import org.glassfish.grizzly.nio.transport.TCPNIOTransport;
-import org.glassfish.grizzly.nio.transport.TCPNIOTransportBuilder;
-import org.glassfish.grizzly.utils.StringFilter;
-
-/**
- * Class initializes and starts the echo server, based on Grizzly 2.0
- *
- * @author Alexey Stashok
- */
-/**
- * @author mercy
- *通过换行去区分一个中断符
- */
-public class GrizzlyEchoServer1 {
- private static final Logger logger = Logger.getLogger(GrizzlyEchoServer1.class.getName());
- public static final String ADDR="127.0.0.1";
- public static final int PORT = 10003;
-
- public static void main(String[] args) throws IOException {
- // Create a FilterChain using FilterChainBuilder
- FilterChainBuilder filterChainBuilder = FilterChainBuilder.stateless();
-
- // Add TransportFilter, which is responsible
- // for reading and writing data to the connection
- filterChainBuilder.add(new TransportFilter());
-
- // StringFilter is responsible for Buffer <-> String conversion
- // filterChainBuilder.add(new StringFilter(Charset.forName("GBK")));
- filterChainBuilder.add(new StringFilter(Charset.forName("GBK"), "\r\n"));
- // EchoFilter is responsible for echoing received messages
- filterChainBuilder.add(new GrizzlyEchoFilter());
-
- // Create TCP transport
- final TCPNIOTransport transport =
- TCPNIOTransportBuilder.newInstance().build();
-
- transport.setProcessor(filterChainBuilder.build());
-
- try {
- // binding transport to start listen on certain host and port
- logger.info("binding transport to start listen on certain host and port");
- transport.bind(ADDR,PORT);
-
- // start the transport
- transport.start();
-
- //logger.info("Press any key to stop the server...");
- System.in.read();
- } finally {
- //logger.info("Stopping transport...");
- // stop the transport
- transport.shutdownNow();
-
- logger.info("Stopped transport...");
- }
- }
-}
\ No newline at end of file
diff --git a/networkProgramming/src/framework/grizzly/ThreadTest.java b/networkProgramming/src/framework/grizzly/ThreadTest.java
deleted file mode 100644
index 97accb5..0000000
--- a/networkProgramming/src/framework/grizzly/ThreadTest.java
+++ /dev/null
@@ -1,103 +0,0 @@
-package framework.grizzly;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.nio.ByteBuffer;
-
-public class ThreadTest{
- class SendThread implements Runnable {
- public SendThread() {
- }
-
- public void run() {
- String f="00000000111111100000000";
- long start=System.currentTimeMillis();
- System.out.println("length:"+f.length());
- String d=new ThreadTest().send("127.0.0.1", 10003, f, 3500);
- System.out.println("result:"+d);
- long end=System.currentTimeMillis();
- System.out.println("COST:"+(end-start));
- }
- }
- public String send(String ip, int port, String sendStr, int timeout) {
- String ENCODING = "GBK";
- if (sendStr == null || "".equals(sendStr)) {
- return "str is null";
- }
- Socket client = null;
- OutputStream stream = null;
- InputStream is = null;
-
- try {
- client = new Socket();
- InetSocketAddress address = new InetSocketAddress(ip, port);
- client.connect(address);
-
- timeout = timeout >= 0 ? timeout : 3500;
- client.setSoTimeout(timeout);
- stream = client.getOutputStream();
- is = client.getInputStream();
-
- int len = 0;
-
- len = sendStr.getBytes(ENCODING).length;
- ByteBuffer buf = ByteBuffer.allocate(len);
- byte[] bytes = sendStr.getBytes(ENCODING);
- buf.put(bytes);
- stream.write(buf.array(), 0, len);
- stream.flush();
- String res = "";
- int i = 0;
- byte[] b = new byte[6555];
- while ((i = is.read(b)) != -1) {
- res = new String(b, 0, i,"GBK");
- break;
- }
- return res;
- } catch (Exception e) {
- StringBuilder strBuilder = new StringBuilder();
- strBuilder.append("error send message1").append(e.getMessage()).append("&errorID=")
- .append(System.currentTimeMillis());
- return strBuilder.toString();
- } finally {
- if (client != null) {
- try {
- client.close();
- } catch (IOException e) {
- StringBuilder strBuilder = new StringBuilder();
- strBuilder.append("error send message2").append(e.getMessage()).append("&errorID=")
- .append(System.currentTimeMillis());
- }
- }
-
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException e) {
- StringBuilder strBuilder = new StringBuilder();
- strBuilder.append("error send message3").append(e.getMessage()).append("&errorID=")
- .append(System.currentTimeMillis());
- }
- }
- if (is != null) {
- try {
- is.close();
- } catch (IOException e) {
- StringBuilder strBuilder = new StringBuilder();
- strBuilder.append("error send message").append(e.getMessage()).append("&errorID=")
- .append(System.currentTimeMillis());
- }
- }
- }
- }
- public void start(){
- new Thread(new SendThread()).start();
- }
- public static void main(String[] args) {
- new ThreadTest().start();
- }
-
-}
diff --git a/networkProgramming/src/framework/mina/EchoClient.java b/networkProgramming/src/framework/mina/EchoClient.java
deleted file mode 100644
index 0a80166..0000000
--- a/networkProgramming/src/framework/mina/EchoClient.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package framework.mina;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.net.Socket;
-
-public class EchoClient {
- private String host="localhost";
- private int port=10003;
- private Socket socket;
- public EchoClient()throws IOException{
- socket=new Socket(host,port);
- //获取绑定后的端口号和绑定前的端口号
- System.out.println("new Connecttion accept" +socket.getInetAddress()+":"+socket.getPort()+",localPort:"+socket.getLocalPort());
- }
- private PrintWriter getWriter(Socket socket) throws IOException{
- OutputStream socketOut=socket.getOutputStream();
- return new PrintWriter(socketOut,true);
- }
- private BufferedReader getReader(Socket socket)throws IOException{
- InputStream socketIn=socket.getInputStream();
- return new BufferedReader(new InputStreamReader(socketIn));
- }
- public void talk() throws IOException{
- try{
- BufferedReader br=getReader(socket);
- PrintWriter pw=getWriter(socket);
- BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
- String msg=null;
- while((msg=reader.readLine())!=null){
- pw.println(msg);
- System.out.println(br.readLine());
- if(msg.equals("bye")){
- break;
- }
- }
- }catch(IOException e){
- e.printStackTrace();
- }
- try{
- socket.close();
- }catch(IOException e){
- e.printStackTrace();
- }
- }
- public static void main(String[] args) throws IOException{
- new EchoClient().talk();
- }
-
-}
diff --git a/networkProgramming/src/framework/mina/MinaClient.java b/networkProgramming/src/framework/mina/MinaClient.java
deleted file mode 100644
index c787a0c..0000000
--- a/networkProgramming/src/framework/mina/MinaClient.java
+++ /dev/null
@@ -1,79 +0,0 @@
-package framework.mina;
-
-import java.net.InetSocketAddress;
-import java.nio.charset.Charset;
-
-import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
-import org.apache.mina.core.future.CloseFuture;
-import org.apache.mina.core.future.ConnectFuture;
-import org.apache.mina.core.session.IoSession;
-import org.apache.mina.filter.codec.ProtocolCodecFilter;
-import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
-import org.apache.mina.filter.logging.LoggingFilter;
-import org.apache.mina.transport.socket.SocketConnector;
-import org.apache.mina.transport.socket.nio.NioSocketConnector;
-
-public class MinaClient {
-
- private SocketConnector connector;
- private ConnectFuture future;
- private IoSession session;
-
- public boolean connect() {
- /*
- * 1.创建一个socket连接,连接到服务器
- */
- connector = new NioSocketConnector();
-
- /*
- * 获取过滤器链,用于添加过滤器
- */
- DefaultIoFilterChainBuilder chain = connector.getFilterChain();
-
- // b.添加日志过滤器
- chain.addLast("logger", new LoggingFilter());
-
- // c.添加字符的编码过滤器
- chain.addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("GBK"))));
-
- /*
- * 3.设置消息处理器,用于处理接收到的消息
- */
- connector.setHandler(new MinaClientHandler());
-
- /*
- * 4.根据IP和端口号连接到服务器
- */
- future = connector.connect(new InetSocketAddress("127.0.0.1", 10003));
- // 等待连接创建完成
- future.awaitUninterruptibly();
-
- /*
- * 5.获取session对象,通过session可以向服务器发送消息;
- */
- session = future.getSession();
- session.getConfig().setUseReadOperation(true);
- return future.isConnected();
- }
-
- /**
- * 往服务器发送消息
- *
- * @param message
- */
- public void sendMsg2Server(String message) {
- session.write(message);
- }
-
- /**
- * 关闭与服务器的连接
- *
- * @return
- */
- public boolean close() {
- CloseFuture future = session.getCloseFuture();
- future.awaitUninterruptibly(1000);
- connector.dispose();
- return true;
- }
-}
diff --git a/networkProgramming/src/framework/mina/MinaClientHandler.java b/networkProgramming/src/framework/mina/MinaClientHandler.java
deleted file mode 100644
index e12796c..0000000
--- a/networkProgramming/src/framework/mina/MinaClientHandler.java
+++ /dev/null
@@ -1,41 +0,0 @@
-package framework.mina;
-
-import org.apache.mina.core.service.IoHandlerAdapter;
-import org.apache.mina.core.session.IoSession;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class MinaClientHandler extends IoHandlerAdapter {
- private static final Logger log = LoggerFactory.getLogger(MinaClientHandler.class);
-
- @Override
- public void exceptionCaught(IoSession session, Throwable cause)
- throws Exception {
- // 出现异常
- log.error("--------exception--------");
- super.exceptionCaught(session, cause);
- }
-
- @Override
- public void messageReceived(IoSession session, Object message)
- throws Exception {
- // 从服务器中接收到消息后的处理
- log.info("--------msg receive--------");
- log.info("Message:{}" + message.toString());
- super.messageReceived(session, message);
- }
-
- @Override
- public void messageSent(IoSession session, Object message) throws Exception {
- // 往服务器中发送消息
- log.info("--------msg sent--------");
- super.messageSent(session, message);
- }
-
- @Override
- public void sessionCreated(IoSession session) throws Exception {
- // 当session被创建的时候调用
- log.info("--------session create--------");
- super.sessionCreated(session);
- }
-}
diff --git a/networkProgramming/src/framework/mina/MinaServer.java b/networkProgramming/src/framework/mina/MinaServer.java
deleted file mode 100644
index 2151bcf..0000000
--- a/networkProgramming/src/framework/mina/MinaServer.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package framework.mina;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.nio.charset.Charset;
-
-import org.apache.mina.core.service.IoAcceptor;
-import org.apache.mina.core.session.IdleStatus;
-import org.apache.mina.filter.codec.ProtocolCodecFilter;
-import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
-import org.apache.mina.filter.logging.LoggingFilter;
-import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
-
-public class MinaServer {
- // 定义监听端口
- private static final int PORT = 10003;
-
- public static void main(String[] args) throws IOException {
- IoAcceptor acceptor = new NioSocketAcceptor();
-
- acceptor.getFilterChain().addLast("logger", new LoggingFilter());
- /*acceptor.getFilterChain().addLast(
- "codec",
- new ProtocolCodecFilter(new TextLineCodecFactory(Charset
- .forName("GBK"))));*/
- acceptor.getFilterChain().addLast("codec",new ProtocolCodecFilter(new TextLineCodecFactory(Charset
- .forName("GBK"),"\r\n","\r\n")));
-
- acceptor.setHandler(new MinaServerHandler());
- acceptor.getSessionConfig().setReadBufferSize(2048);
- acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
- acceptor.bind(new InetSocketAddress(PORT));
- }
- }
\ No newline at end of file
diff --git a/networkProgramming/src/framework/mina/MinaServer1.java b/networkProgramming/src/framework/mina/MinaServer1.java
deleted file mode 100644
index d23216b..0000000
--- a/networkProgramming/src/framework/mina/MinaServer1.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package framework.mina;
-
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.nio.charset.Charset;
-
-import org.apache.mina.core.service.IoAcceptor;
-import org.apache.mina.core.session.IdleStatus;
-import org.apache.mina.filter.codec.ProtocolCodecFilter;
-import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
-import org.apache.mina.filter.logging.LoggingFilter;
-import org.apache.mina.filter.stream.StreamWriteFilter;
-import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
-
-public class MinaServer1 {
- // 定义监听端口
- private static final int PORT = 10003;
-
- public static void main(String[] args) throws IOException {
- IoAcceptor acceptor = new NioSocketAcceptor();
-
- acceptor.getFilterChain().addLast("logger", new LoggingFilter());
- acceptor.getFilterChain().addLast("ddd", new StreamWriteFilter());
- //acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("GBK"))));
- acceptor.setHandler(new MinaServerHandler1());
- acceptor.getSessionConfig().setReadBufferSize(2048);
- acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
- acceptor.bind(new InetSocketAddress(PORT));
- System.out.println("PORT IS START......");
- }
- }
\ No newline at end of file
diff --git a/networkProgramming/src/framework/mina/MinaServerHandler.java b/networkProgramming/src/framework/mina/MinaServerHandler.java
deleted file mode 100644
index f96431c..0000000
--- a/networkProgramming/src/framework/mina/MinaServerHandler.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package framework.mina;
-
-import java.util.Date;
-
-import org.apache.mina.core.service.IoHandlerAdapter;
-import org.apache.mina.core.session.IdleStatus;
-import org.apache.mina.core.session.IoSession;
-
-public class MinaServerHandler extends IoHandlerAdapter {
- @Override
- public void exceptionCaught(IoSession session, Throwable cause)
- throws Exception {
- cause.printStackTrace();
- }
-
- @Override
- public void messageReceived(IoSession session, Object message)
- throws Exception {
- String string=message.toString();
- if (string.trim().equalsIgnoreCase("quit")) {
- session.close(true);
- return;
- }
- System.out.println("recevied message:"+string);
- String reply=" hi, i am server";
- session.write(reply);
- System.out.println("message have been written");
- }
-
- @Override
- public void sessionIdle(IoSession session, IdleStatus status)
- throws Exception {
- System.out.println("IDLE " + session.getIdleCount(status));
- }
- }
\ No newline at end of file
diff --git a/networkProgramming/src/framework/mina/MinaServerHandler1.java b/networkProgramming/src/framework/mina/MinaServerHandler1.java
deleted file mode 100644
index 996e927..0000000
--- a/networkProgramming/src/framework/mina/MinaServerHandler1.java
+++ /dev/null
@@ -1,61 +0,0 @@
-package framework.mina;
-
-import java.io.ByteArrayOutputStream;
-import java.io.DataOutputStream;
-import java.nio.ByteBuffer;
-import java.util.Date;
-
-import org.apache.mina.core.buffer.IoBuffer;
-import org.apache.mina.core.service.IoHandlerAdapter;
-import org.apache.mina.core.session.IdleStatus;
-import org.apache.mina.core.session.IoSession;
-import org.apache.mina.filter.codec.ProtocolEncoderOutput;
-
-public class MinaServerHandler1 extends IoHandlerAdapter {
- @Override
- public void exceptionCaught(IoSession session, Throwable cause)
- throws Exception {
- cause.printStackTrace();
- }
-
- @Override
- public void messageReceived(IoSession session, Object message)
- throws Exception {
- IoBuffer buffer=(IoBuffer)message;
- ByteBuffer bf= buffer.buf();
- byte[] tempBuffer=new byte[bf.limit()];
- bf.get(tempBuffer);
- //GBK字符转换
- String str=new String(tempBuffer,"GBK");
- System.out.println("receive:"+str+"\nreceive's length:"+str.length());
- String reply="hi, i am server你好";
- //session.write(reply);
- ByteArrayOutputStream outputPacket = new ByteArrayOutputStream();
- DataOutputStream dos = new DataOutputStream(outputPacket);
- byte[] bytes = reply.getBytes("GBK");
- int len= reply.getBytes("GBK").length;
- System.out.println("reply's length:"+len);
- dos.write(bytes,0,len);
- //dos.writeUTF(reply);
- dos.flush();
- System.out.println(outputPacket.toByteArray().length);
- IoBuffer b = IoBuffer.allocate(6000);
- System.out.println("length:"+outputPacket.toByteArray().length);
- System.out.println(b.limit());
- b.put(outputPacket.toByteArray());
- b.flip();
- System.out.println(b.limit());
- session.write(b);
- }
- public ByteBuffer getByteBuffer(String str) {
-
- return ByteBuffer.wrap(str.getBytes());
-
- }
-
- @Override
- public void sessionIdle(IoSession session, IdleStatus status)
- throws Exception {
- System.out.println("IDLE " + session.getIdleCount(status));
- }
- }
\ No newline at end of file
diff --git a/networkProgramming/src/framework/mina/MinaTest.java b/networkProgramming/src/framework/mina/MinaTest.java
deleted file mode 100644
index a1b8220..0000000
--- a/networkProgramming/src/framework/mina/MinaTest.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package framework.mina;
-
-public class MinaTest {
- public static void main(String[] args) {
- MinaClient c=new MinaClient();
- c.connect();
- c.sendMsg2Server("-----00009999-----");
- }
-
-}
diff --git a/networkProgramming/src/framework/mina/ThreadTest.java b/networkProgramming/src/framework/mina/ThreadTest.java
deleted file mode 100644
index 449a35d..0000000
--- a/networkProgramming/src/framework/mina/ThreadTest.java
+++ /dev/null
@@ -1,107 +0,0 @@
-package framework.mina;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.nio.ByteBuffer;
-
-/**
- * @author mercy
- * mina要加上换行才能收到数据\n或者\r\n
- */
-public class ThreadTest{
- class SendThread implements Runnable {
- public SendThread() {
- }
-
- public void run() {
- String f="00000000111111100000000\n";
- long start=System.currentTimeMillis();
- System.out.println("length:"+f.length());
- String d=new ThreadTest().send("127.0.0.1", 10003, f, 3500);
- System.out.println("result:"+d);
- long end=System.currentTimeMillis();
- System.out.println("COST:"+(end-start));
- }
- }
- public String send(String ip, int port, String sendStr, int timeout) {
- String ENCODING = "GBK";
- if (sendStr == null || "".equals(sendStr)) {
- return "str is null";
- }
- Socket client = null;
- OutputStream stream = null;
- InputStream is = null;
-
- try {
- client = new Socket();
- InetSocketAddress address = new InetSocketAddress(ip, port);
- client.connect(address);
-
- timeout = timeout >= 0 ? timeout : 3500;
- client.setSoTimeout(timeout);
- stream = client.getOutputStream();
- is = client.getInputStream();
-
- int len = 0;
-
- len = sendStr.getBytes(ENCODING).length;
- ByteBuffer buf = ByteBuffer.allocate(len);
- byte[] bytes = sendStr.getBytes(ENCODING);
- buf.put(bytes);
- stream.write(buf.array(), 0, len);
- stream.flush();
- String res = "";
- int i = 0;
- byte[] b = new byte[6555];
- while ((i = is.read(b)) != -1) {
- res = new String(b, 0, i,"GBK");
- break;
- }
- return res;
- } catch (Exception e) {
- StringBuilder strBuilder = new StringBuilder();
- strBuilder.append("error send message1").append(e.getMessage()).append("&errorID=")
- .append(System.currentTimeMillis());
- return strBuilder.toString();
- } finally {
- if (client != null) {
- try {
- client.close();
- } catch (IOException e) {
- StringBuilder strBuilder = new StringBuilder();
- strBuilder.append("error send message2").append(e.getMessage()).append("&errorID=")
- .append(System.currentTimeMillis());
- }
- }
-
- if (stream != null) {
- try {
- stream.close();
- } catch (IOException e) {
- StringBuilder strBuilder = new StringBuilder();
- strBuilder.append("error send message3").append(e.getMessage()).append("&errorID=")
- .append(System.currentTimeMillis());
- }
- }
- if (is != null) {
- try {
- is.close();
- } catch (IOException e) {
- StringBuilder strBuilder = new StringBuilder();
- strBuilder.append("error send message").append(e.getMessage()).append("&errorID=")
- .append(System.currentTimeMillis());
- }
- }
- }
- }
- public void start(){
- new Thread(new SendThread()).start();
- }
- public static void main(String[] args) {
- new ThreadTest().start();
- }
-
-}
diff --git a/networkProgramming/src/framework/netty/EchoClient.java b/networkProgramming/src/framework/netty/EchoClient.java
deleted file mode 100644
index 46bdfae..0000000
--- a/networkProgramming/src/framework/netty/EchoClient.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package framework.netty;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.net.Socket;
-
-public class EchoClient {
- private String host="localhost";
- private int port=10003;
- private Socket socket;
- public EchoClient()throws IOException{
- socket=new Socket(host,port);
- //获取绑定后的端口号和绑定前的端口号
- System.out.println("new Connecttion accept" +socket.getInetAddress()+":"+socket.getPort()+",localPort:"+socket.getLocalPort());
- }
- private PrintWriter getWriter(Socket socket) throws IOException{
- OutputStream socketOut=socket.getOutputStream();
- return new PrintWriter(socketOut,true);
- }
- private BufferedReader getReader(Socket socket)throws IOException{
- InputStream socketIn=socket.getInputStream();
- return new BufferedReader(new InputStreamReader(socketIn));
- }
- public void talk() throws IOException{
- try{
- BufferedReader br=getReader(socket);
- PrintWriter pw=getWriter(socket);
- BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
- String msg=null;
- while((msg=reader.readLine())!=null){
- pw.println(msg);
- System.out.println(br.readLine());
- if(msg.equals("bye")){
- break;
- }
- }
- }catch(IOException e){
- e.printStackTrace();
- }
- try{
- socket.close();
- }catch(IOException e){
- e.printStackTrace();
- }
- }
- public static void main(String[] args) throws IOException{
- new EchoClient().talk();
- }
-
-}
diff --git a/networkProgramming/src/framework/netty/NettyServer.java b/networkProgramming/src/framework/netty/NettyServer.java
deleted file mode 100644
index 7321f53..0000000
--- a/networkProgramming/src/framework/netty/NettyServer.java
+++ /dev/null
@@ -1,76 +0,0 @@
-package framework.netty;
-
-import java.nio.charset.Charset;
-
-import org.apache.log4j.Logger;
-import org.springframework.context.support.ClassPathXmlApplicationContext;
-
-import com.eshore.ismp.hbinterface.service.BizCommonService;
-
-import io.netty.bootstrap.ServerBootstrap;
-import io.netty.channel.ChannelInitializer;
-import io.netty.channel.ChannelPipeline;
-import io.netty.channel.EventLoopGroup;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.channel.socket.SocketChannel;
-import io.netty.channel.socket.nio.NioServerSocketChannel;
-import io.netty.handler.codec.string.StringDecoder;
-import io.netty.handler.codec.string.StringEncoder;
-
-public class NettyServer {
- private static final Logger logger = Logger.getLogger(NettyServer.class);
- private static int PORT = 10003;
- /**用于分配处理业务线程的线程组个数 */
- protected static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors()*2; //默认
- /** 业务出现线程大小*/
- protected static final int BIZTHREADSIZE = 4;
- /*
- * NioEventLoopGroup实际上就是个线程池,
- * NioEventLoopGroup在后台启动了n个NioEventLoop来处理Channel事件,
- * 每一个NioEventLoop负责处理m个Channel,
- * NioEventLoopGroup从NioEventLoop数组里挨个取出NioEventLoop来处理Channel
- */
- private static final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
- private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE);
-
- protected static void run(final BizCommonService bizCommonService) throws Exception {
- //String PORTs=ConfigLoadUtil.getValue("toCrmServerPort");
- //PORT=Integer.parseInt(PORTs);
- logger.info("PORT IS:"+PORT);
- //System.out.println("start main 7......PORT="+PORT);
- ServerBootstrap b = new ServerBootstrap();
- b.group(bossGroup, workerGroup);
- b.channel(NioServerSocketChannel.class);
- b.childHandler(new ChannelInitializer() {
- @Override
- public void initChannel(SocketChannel ch) throws Exception {
- ChannelPipeline pipeline = ch.pipeline();
- /* pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
- pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8)); */
- pipeline.addLast("decoder", new StringDecoder(Charset.forName("GBK")));
- pipeline.addLast("encoder", new StringEncoder(Charset.forName("GBK")));
- pipeline.addLast(new NettyServerHandler(bizCommonService));
- }
- });
- b.bind(PORT).sync();
- logger.info("TCP服务器已启动");
- }
-
- protected static void shutdown() {
- workerGroup.shutdownGracefully();
- bossGroup.shutdownGracefully();
- }
-
- public static void main(String[] args) throws Exception {
- try{
- ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
- new String[] { "applicationContext.xml" });
- BizCommonService bizCommonService = (BizCommonService) context.getBean("bizCommonService");
- context.start();
- NettyServer.run(bizCommonService);
- }catch(Exception e){
- logger.error("start crm interface error:",e);
- System.exit(-1);
- }
- }
-}
diff --git a/networkProgramming/src/framework/netty/NettyServerHandler.java b/networkProgramming/src/framework/netty/NettyServerHandler.java
deleted file mode 100644
index 5bfe16b..0000000
--- a/networkProgramming/src/framework/netty/NettyServerHandler.java
+++ /dev/null
@@ -1,40 +0,0 @@
-package framework.netty;
-
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.SimpleChannelInboundHandler;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-public class NettyServerHandler extends SimpleChannelInboundHandler