加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

netty处理客户端传过来的get、post、websocket数据例子

发布时间:2020-05-24 21:40:07 所属栏目:Java 来源:互联网
导读:netty处理客户端传过来的get、post、websocket数据例子

下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。

脚本之家小编现在分享给大家,也给大家做个参考。

用neety作为http服务器,在服务器端读取客户端传过来的get和post参数和websocket数据例子,netty版本3.6.6
packagecom.penngo.http;
importjava.net.InetSocketAddress;
importjava.util.concurrent.Executors;
importorg.jboss.netty.bootstrap.ServerBootstrap;
importorg.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

publicclassHttpServer{

privatefinalintport;

publicHttpServer(intport){
this.port=port;
}

publicvoidrun(){
ServerBootstrapbootstrap=newServerBootstrap(newNioServerSocketChannelFactory(
Executors.newCachedThreadPool(),Executors.newCachedThreadPool()));
bootstrap.setPipelineFactory(newHttpServerPipelineFactory());

bootstrap.bind(newInetSocketAddress(port));
System.out.println("Websocketserverstartedatport"+port+'.');
System.out.println("Openyourbrowserandnavigatetohttp://localhost:"+port+'/');
}

publicstaticvoidmain(String[]args){
intport;
if(args.length>0){
port=Integer.parseInt(args[0]);
}else{
port=8080;
}
newHttpServer(port).run();
}
}
packagecom.penngo.http;
importjava.util.List;
importjava.util.Map;
importorg.jboss.netty.buffer.ChannelBuffer;
importorg.jboss.netty.buffer.ChannelBuffers;
importorg.jboss.netty.channel.ChannelFuture;
importorg.jboss.netty.channel.ChannelFutureListener;
importorg.jboss.netty.channel.ChannelHandlerContext;
importorg.jboss.netty.channel.ExceptionEvent;
importorg.jboss.netty.channel.MessageEvent;
importorg.jboss.netty.channel.SimpleChannelUpstreamHandler;
importorg.jboss.netty.handler.codec.http.DefaultHttpResponse;
importorg.jboss.netty.handler.codec.http.HttpRequest;
importorg.jboss.netty.handler.codec.http.HttpResponse;
importorg.jboss.netty.handler.codec.http.QueryStringDecoder;
importorg.jboss.netty.handler.codec.http.multipart.Attribute;
importorg.jboss.netty.handler.codec.http.multipart.DefaultHttpDataFactory;
importorg.jboss.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
importorg.jboss.netty.handler.codec.http.multipart.InterfaceHttpData;
importorg.jboss.netty.handler.codec.http.multipart.InterfaceHttpData.HttpDataType;
importorg.jboss.netty.handler.codec.http.websocketx.CloseWebSocketFrame;
importorg.jboss.netty.handler.codec.http.websocketx.PingWebSocketFrame;
importorg.jboss.netty.handler.codec.http.websocketx.PongWebSocketFrame;
importorg.jboss.netty.handler.codec.http.websocketx.TextWebSocketFrame;
importorg.jboss.netty.handler.codec.http.websocketx.WebSocketFrame;
importorg.jboss.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
importorg.jboss.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;

importorg.jboss.netty.util.CharsetUtil;

importstaticorg.jboss.netty.handler.codec.http.HttpHeaders.Names.*;
importstaticorg.jboss.netty.handler.codec.http.HttpHeaders.*;
importstaticorg.jboss.netty.handler.codec.http.HttpMethod.*;
importstaticorg.jboss.netty.handler.codec.http.HttpResponseStatus.*;
importstaticorg.jboss.netty.handler.codec.http.HttpVersion.*;

publicclassHttpServerHandlerextendsSimpleChannelUpstreamHandler{
	privateWebSocketServerHandshakerhandshaker;
	privatestaticfinalStringWEBSOCKET_PATH="/websocket";
	@Override
	publicvoidmessageReceived(ChannelHandlerContextctx,MessageEvente)
			throwsException{
		Objectmsg=e.getMessage();
		if(msginstanceofHttpRequest){
			handleHttpRequest(ctx,(HttpRequest)msg);
		}elseif(msginstanceofWebSocketFrame){
			handleWebSocketFrame(ctx,(WebSocketFrame)msg);
		}
	}

	privatevoidhandleHttpRequest(ChannelHandlerContextctx,HttpRequestreq)
			throwsException{
		System.out.println("handleHttpRequestmethod=========="+req.getMethod());
		System.out.println("handleHttpRequesturi=========="+req.getUri());
		if(req.getMethod()==GET){//处理get请求
			if(req.getUri().equals("/websocket")){
				//Handshake
		WebSocketServerHandshakerFactorywsFactory=newWebSocketServerHandshakerFactory(
		getWebSocketLocation(req),null,false);
		handshaker=wsFactory.newHandshaker(req);
		if(handshaker==null){
		wsFactory.sendUnsupportedWebSocketVersionResponse(ctx.getChannel());
		}else{
		handshaker.handshake(ctx.getChannel(),req).addListener(WebSocketServerHandshaker.HANDSHAKE_LISTENER);
		}
			}
			else{
				QueryStringDecoderdecoder=newQueryStringDecoder(req.getUri());
				Map<String,List<String>>parame=decoder.getParameters();
				List<String>q=parame.get("q");//读取从客户端传过来的参数
				Stringquestion=q.get(0);
				if(question!=null&&!question.equals("")){
					System.out.println("r:"+question);
					HttpResponseres=newDefaultHttpResponse(HTTP_1_1,OK);
					Stringdata="<html><body>你好,GET</body><html>";
					ChannelBuffercontent=ChannelBuffers.copiedBuffer(data,CharsetUtil.UTF_8);
					res.setHeader(CONTENT_TYPE,"text/html;charset=UTF-8");
					res.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN,"*");
					setContentLength(res,content.readableBytes());
					res.setContent(content);
					sendHttpResponse(ctx,req,res);
				}
			}
		}
		if(req.getMethod()==POST){//处理POST请求
			HttpPostRequestDecoderdecoder=newHttpPostRequestDecoder(
					newDefaultHttpDataFactory(false),req);
			InterfaceHttpDatapostData=decoder.getBodyHttpData("q");////
																		//读取从客户端传过来的参数
			Stringquestion="";
			if(postData.getHttpDataType()==HttpDataType.Attribute){
				Attributeattribute=(Attribute)postData;
				question=attribute.getValue();
				System.out.println("q:"+question);

			}
			if(question!=null&&!question.equals("")){

				HttpResponseres=newDefaultHttpResponse(HTTP_1_1,OK);
				Stringdata="<html><body>你好,POST</body><html>";
				ChannelBuffercontent=ChannelBuffers.copiedBuffer(data,CharsetUtil.UTF_8);
				res.setHeader(CONTENT_TYPE,"text/html;charset=UTF-8");
				res.setHeader(ACCESS_CONTROL_ALLOW_ORIGIN,"*");
				setContentLength(res,content.readableBytes());
				res.setContent(content);
				sendHttpResponse(ctx,res);

			}
			return;
		}
	}

	@Override
	publicvoidexceptionCaught(ChannelHandlerContextctx,ExceptionEvente)
			throwsException{
		e.getCause().printStackTrace();
		e.getChannel().close();
	}
	privatevoidhandleWebSocketFrame(ChannelHandlerContextctx,WebSocketFrameframe){
	if(frameinstanceofCloseWebSocketFrame){
	handshaker.close(ctx.getChannel(),(CloseWebSocketFrame)frame);
	return;
	}
	if(frameinstanceofPingWebSocketFrame){
	ctx.getChannel().write(newPongWebSocketFrame(frame.getBinaryData()));
	return;
	}
	if(!(frameinstanceofTextWebSocketFrame)){
	thrownewUnsupportedOperationException(String.format("%sframetypesnotsupported",frame.getClass()
	.getName()));
	}
	Stringrequest=((TextWebSocketFrame)frame).getText();
	System.out.println("收到socketmsg="+request);
	request="这是来自服务器端的数据";
	ctx.getChannel().write(newTextWebSocketFrame(request.toUpperCase()));
	}
	privatestaticvoidsendHttpResponse(ChannelHandlerContextctx,HttpRequestreq,HttpResponseres){
		if(res.getStatus().getCode()!=200){
			res.setContent(ChannelBuffers.copiedBuffer(res.getStatus()
					.toString(),CharsetUtil.UTF_8));
			setContentLength(res,res.getContent().readableBytes());
		}

		ChannelFuturef=ctx.getChannel().write(res);
		if(!isKeepAlive(req)||res.getStatus().getCode()!=200){
			f.addListener(ChannelFutureListener.CLOSE);
		}
	}
	privatestaticStringgetWebSocketLocation(HttpRequestreq){
	return"ws://"+req.getHeader(HOST)+WEBSOCKET_PATH;
	}
}
packagecom.penngo.http;
importstaticorg.jboss.netty.channel.Channels.*;
importorg.jboss.netty.channel.ChannelPipeline;
importorg.jboss.netty.channel.ChannelPipelineFactory;
importorg.jboss.netty.handler.codec.http.HttpChunkAggregator;
importorg.jboss.netty.handler.codec.http.HttpRequestDecoder;
importorg.jboss.netty.handler.codec.http.HttpResponseEncoder;

publicclassHttpServerPipelineFactoryimplementsChannelPipelineFactory{
publicChannelPipelinegetPipeline()throwsException{
//Createadefaultpipelineimplementation.
ChannelPipelinepipeline=pipeline();
pipeline.addLast("decoder",newHttpRequestDecoder());
//pipeline.addLast("aggregator",newHttpChunkAggregator(65536));
pipeline.addLast("encoder",newHttpResponseEncoder());
pipeline.addLast("handler",newHttpServerHandler());
returnpipeline;
}
}
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf-8">
<title>WebSocketExample</title>
<scriptsrc="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"type="text/javascript"></script>
<style>
textarea{
width:500px;
height:100px;
}
</style>
<script>
$(function(){

varSock=function(){
varsocket;
if(!window.WebSocket){
window.WebSocket=window.MozWebSocket;
}

if(window.WebSocket){
socket=newWebSocket("ws://localhost:8080/websocket");
socket.onopen=onopen;
socket.onmessage=onmessage;
socket.onclose=onclose;
}else{
alert("YourbrowserdoesnotsupportWebSocket.");
}

functiononopen(event){
getTextAreaElement().value="WebSocketopened!";
}

functiononmessage(event){
appendTextArea(event.data);
}

functiononclose(event){
appendTextArea("WebSocketclosed");
}

functionappendTextArea(newData){
varel=getTextAreaElement();
el.value=el.value+'n'+newData;
}

functiongetTextAreaElement(){
returndocument.getElementById('responseText');
}

functionsend(event){
event.preventDefault();
if(window.WebSocket){
if(socket.readyState==WebSocket.OPEN){
socket.send(event.target.message.value);
}else{
alert("Thesocketisnotopen.");
}
}
}
document.forms.inputform.addEventListener('submit',send,false);
}
window.addEventListener('load',function(){
newSock();
},false);

$("#btnGet").click(function(){
$.get("http://localhost:8080/",{q:"John"},function(data){
$("#responseTextGet").val($("#responseTextGet").val()+data)
});
});
$("#btnPost").click(function(){
$.post("http://localhost:8080/",function(data){
$("#responseTextPost").val($("#responseTextGet").val()+data)
});
});
});

</script>
</head>
<body>
<h3>输入内容</h3>
<formname="inputform">
<inputtype="text"name="message"id="message"placeholder="Entertexttobesent"autofocus>
<inputtype="submit"value="发送WebSocket数据">
</form>
<h3>服务端返回</h3>
<textareaid="responseText"></textarea>
<h3>输入内容</h3>
<formname="inputform">
<inputtype="text"name="message"id="messageGet"placeholder="Entertexttobesent"autofocus>
<inputtype="button"value="Get数据"id="btnGet">
</form>
<h3>服务端返回</h3>
<textareaid="responseTextGet"></textarea>
<h3>输入内容</h3>
<formname="inputform">
<inputtype="text"name="message"id="messagePost"placeholder="Entertexttobesent"autofocus>
<inputtype="button"value="Post数据"id="btnPost">
</form>
<h3>服务端返回</h3>
<textareaid="responseTextPost"></textarea>
</body>
</html>

以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读