项目需求:需要建立socket客户端完成连接,成功连接后服务端会循环发送数据HTTP格式字符串到客户端,客户端获取HTTP处理获得其中的body数据。
描述能力太差,我直接贴使用实例吧!!!
一、获取连接,并启用一个线程:
/**
* @author spd
* 通过ip,port连接到socket
*
* */
public class ConnectMethod {
Socket client = null;
MsgListener lis;//此类为监听所获得的msg内容做处理
public ConnectMethod(MsgListener lis){
this.lis = lis;
}
/*
* 连接sokcet
* @param ip/port
* */
public boolean connect(String ip, int port) {
try {
client = new Socket(ip,port); //创建一个socket绑定的端口和地址
OutputStream ops = client.getOutputStream();
//此处可以收发指令用于验证
InputStreamReader ir = new InputStreamReader(client.getInputStream());
BufferedReader bf = new BufferedReader(ir);
//启动服务建立实时监听客服端
new ServerListener(client,lis).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("连接超时");
return false;
}
return true;
}
}
二、循环读取导入parseNext
package com.th.resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.nio.ByteBuffer;
import org.eclipse.jetty.http.HttpParser;
public class ServerListener extends Thread{
Socket socket;
MsgListener lis;
JadkHandler adkHandler = new JadkHandler();
HttpParser httpParser = new HttpParser(adkHandler);
public ServerListener(Socket s,MsgListener lis){
this.socket = s;
this.lis = lis;
}
/**
* 启动监听线程
* */
@Override
public void run() {
Socket client = socket;
httpParser.setHeadResponse(true);
adkHandler.setHost(this);
ByteBuffer bbuffer = ByteBuffer.allocate(1000);
try {
while(true){
// // 如果超过这个时间没有新的数据,则不再继续等待数据
// socket.setSoTimeout(1000);
System.out.println("监听到消息-------");
InputStreamReader isReader = new InputStreamReader(client.getInputStream());
// socket.shutdownOutput();
BufferedReader reader = new BufferedReader(isReader);
int length = 0;
String str= "";
char[] ch = new char[500];
char[] chlen = new char[499];
while (reader.read() !=-1){
reader.read(chlen);
isReader.read(ch);
str = new String(ch);
bbuffer.put(str.getBytes());
bbuffer.flip();
boolean flag = httpParser.parseNext(bbuffer);
bbuffer.compact();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
三、实现HttpParser.RequestHandler,通过重写messageComplete(),控制完成的数据发送到MsgListener监听方法中
package com.th.resource;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpParser;
import org.eclipse.jetty.http.HttpVersion;
public class JadkHandler implements HttpParser.RequestHandler{
private HttpParser host = null;
private StringBuffer completeChunk;
private static MsgListener msgListener;
public void setCompleteChunk(StringBuffer a) {
if(completeChunk != null) {
this.completeChunk = completeChunk.append(a);
}else {
this.completeChunk = a;
}
}
public void setHost(ServerListener a) {
this.host = a.httpParser;
this.msgListener = a.lis;
}
@Override
public void badMessage(int arg0, String arg1);
@Override
public void earlyEOF();
@Override
public int getHeaderCacheSize();
@Override
public boolean headerComplete();
@Override
public boolean messageComplete() {
// TODO Auto-generated method stub
host.reset();
String str = completeChunk.toString();
completeChunk.setLength(0);
msgListener.onData(str);
System.out.println("messageComplete");
return false;
}
@Override
public boolean content(ByteBuffer arg0) {
// TODO Auto-generated method stub
ByteBuffer con = (ByteBuffer) arg0;
//下面这两个是把缓冲区的数据打印下来
Charset charset = Charset.forName("UTF-8");
try {
String str = charset.newDecoder().decode(con).toString();
setCompleteChunk(new StringBuffer(str));
} catch (CharacterCodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
return false;
}
@Override
public boolean contentComplete();
@Override
public void parsedHeader(HttpField arg0);
@Override
public boolean startRequest(String arg0, String arg1, HttpVersion arg2);
}
测试部分:
public class test {
public static void main(String[] args) {
String ip = "192.168.1.1";
int port = 8080;
MsgListener getListener = new GetListener();
ConnectMethod cMethod = new ConnectMethod(getListener);
cMethod.connect(ip, port);
}
}
public class GetListener implements MsgListener{
@Override
public void onData(String msg) {
// TODO Auto-generated method stub
System.out.println("———————————————start———————————————");
System.out.println(msg);
System.out.println("———————————————end———————————————");
}
}
不出意外应该就输出你想要的东西了!!!
附:
环境jdk1.8
引用jar包jetty-http-9.4.15、jetty-io-9.4.15、jetty-util-9.4.15