java socket 长连接
最近做SSO的项目,其中用到了socket长连接.一直都是看代码的,但是要求socket做成SSL的,不得不动手写写代码了.下面我给出一个简单的socket长连接.
Java代码
- SocketClient.java
Java代码
- import
- import
- import
- import
- import
- import
- import
- import
- import
- import
- /*{ user:jiangwh }*/
- public class
- public static final Object locked = new
- public static final BlockingQueue<String> queue = new
- 1024 * 100);
- class SendThread extends
- private
- public
- this.socket = socket;
- }
- @Override
- public void
- while(true){
- try
- String send = getSend();
- new PrintWriter(new
- pw.write(send);
- pw.flush();
- catch
- e.printStackTrace();
- }
- }
- }
- public String getSend() throws
- 1000);
- return "<SOAP-ENV:Envelope>"+System.currentTimeMillis()+"</SOAP-ENV:Envelope>";
- }
- }
- class ReceiveThread extends
- private
- public
- this.socket = socket;
- }
- @Override
- public void
- while(true){
- try
- new
- 8192);
- int index = -1;
- while((index=reader.read(charBuffer))!=-1){
- charBuffer.flip();
- "client:"+charBuffer.toString());
- }
- catch
- e.printStackTrace();
- }
- }
- }
- }
- public void start() throws
- new Socket("10.10.148.40",18889);
- new
- new
- }
- public static void main(String[] args) throws
- new
- }
- }
Java代码
- SocketServer.java
Java代码
- import
- import
- import
- import
- import
- import
- import
- import
- import
- import
- /*{user:jiangwh }*/
- public class
- private final static String SOAP_BEGIN = "<SOAP-ENV:Envelope";
- private final static String SOAP_END = "</SOAP-ENV:Envelope>";
- public static void main(String[] args) throws
- new
- socketServer.start();
- }
- public void start() throws
- new ServerSocket(18889);
- while (true) {
- Socket socket = serverSocket.accept();
- new
- }
- }
- class SocketThread extends
- private
- private
- public
- return
- }
- public void
- this.socket = socket;
- }
- public
- this.socket = socket;
- }
- public void
- try
- new
- new PrintWriter(new
- "GBK"));
- 8192);
- int readIndex = -1;
- while ((readIndex = reader.read(charBuffer)) != -1) {
- charBuffer.flip();
- temp += charBuffer.toString();
- if (temp.indexOf(SOAP_BEGIN) != -1
- 1) {
- // 传送一个soap报文
- new Date().toLocaleString()+"server:"+temp);
- "";
- "receive the soap message");
- writer.flush();
- else if (temp.indexOf(SOAP_BEGIN) != -1) {
- // 包含开始,但不包含
- temp = temp.substring(temp.indexOf(SOAP_BEGIN));
- }
- if (temp.length() > 1024 * 16) {
- break;
- }
- }
- catch
- e.printStackTrace();
- finally
- if (socket != null) {
- if
- try
- socket.close();
- catch
- e.printStackTrace();
- }
- }
- }
- }
- }
- }
- }