├── .gitignore ├── NioTest10.txt ├── NioTest13_In.txt ├── NioTest13_Out.txt ├── NioTest2.txt ├── NioTest3.txt ├── NioTest9.txt ├── README.md ├── build.gradle ├── gen-java └── thrift │ └── generated │ ├── DataException.java │ ├── Person.java │ └── PersonService.java ├── gen-py ├── __init__.py └── py │ ├── __init__.py │ └── thrift │ ├── __init__.py │ └── generated │ ├── PersonService-remote │ ├── PersonService.py │ ├── __init__.py │ ├── constants.py │ └── ttypes.py ├── input.txt ├── input2.txt ├── output.txt ├── output2.txt ├── settings.gradle └── src ├── main ├── java │ ├── com │ │ ├── shengsiyuan │ │ │ ├── decorator │ │ │ │ ├── Client.java │ │ │ │ ├── Component.java │ │ │ │ ├── ConcreteComponent.java │ │ │ │ ├── ConcreteDecorator1.java │ │ │ │ ├── ConcreteDecorator2.java │ │ │ │ └── Decorator.java │ │ │ ├── grpc │ │ │ │ ├── GrpcClient.java │ │ │ │ ├── GrpcServer.java │ │ │ │ └── StudentServiceImpl.java │ │ │ ├── netty │ │ │ │ ├── bytebuf │ │ │ │ │ ├── AtomicUpdaterTest.java │ │ │ │ │ ├── ByteBufTest0.java │ │ │ │ │ ├── ByteBufTest1.java │ │ │ │ │ └── ByteBufTest2.java │ │ │ │ ├── fifthexample │ │ │ │ │ ├── MyServer.java │ │ │ │ │ ├── TextWebSocketFrameHandler.java │ │ │ │ │ └── WebSocketChannelInitializer.java │ │ │ │ ├── firstexample │ │ │ │ │ ├── TestHttpServerHandler.java │ │ │ │ │ ├── TestServer.java │ │ │ │ │ └── TestServerInitializer.java │ │ │ │ ├── fourthexample │ │ │ │ │ ├── MyServer.java │ │ │ │ │ ├── MyServerHandler.java │ │ │ │ │ └── MyServerInitializer.java │ │ │ │ ├── handler │ │ │ │ │ ├── MyByteToLongDecoder.java │ │ │ │ │ ├── MyByteToLongDecoder2.java │ │ │ │ │ ├── MyClient.java │ │ │ │ │ ├── MyClientHandler.java │ │ │ │ │ ├── MyClientInitializer.java │ │ │ │ │ ├── MyLongToByteEncoder.java │ │ │ │ │ ├── MyLongToStringDecoder.java │ │ │ │ │ ├── MyServer.java │ │ │ │ │ ├── MyServerHandler.java │ │ │ │ │ └── MyServerInitializer.java │ │ │ │ ├── handler2 │ │ │ │ │ ├── MyClient.java │ │ │ │ │ ├── MyClientHandler.java │ │ │ │ │ ├── MyClientInitializer.java │ │ │ │ │ ├── MyServer.java │ │ │ │ │ ├── MyServerHandler.java │ │ │ │ │ └── MyServerInitializer.java │ │ │ │ ├── handler3 │ │ │ │ │ ├── MyClient.java │ │ │ │ │ ├── MyClientHandler.java │ │ │ │ │ ├── MyPersonDecoder.java │ │ │ │ │ ├── MyPersonEncoder.java │ │ │ │ │ ├── MyServer.java │ │ │ │ │ ├── MyServerHandler.java │ │ │ │ │ ├── MyServerInitializer.java │ │ │ │ │ └── PersonProtocol.java │ │ │ │ ├── secondexample │ │ │ │ │ ├── MyClient.java │ │ │ │ │ ├── MyClientHandler.java │ │ │ │ │ ├── MyClientInitializer.java │ │ │ │ │ ├── MyServer.java │ │ │ │ │ ├── MyServerHandler.java │ │ │ │ │ └── MyServerInitializer.java │ │ │ │ ├── sixthexample │ │ │ │ │ ├── MyDataInfo.java │ │ │ │ │ ├── TestClient.java │ │ │ │ │ ├── TestClientHandler.java │ │ │ │ │ ├── TestClientInitializer.java │ │ │ │ │ ├── TestServer.java │ │ │ │ │ ├── TestServerHandler.java │ │ │ │ │ └── TestServerInitializer.java │ │ │ │ ├── test │ │ │ │ │ └── Test.java │ │ │ │ └── thirdexample │ │ │ │ │ ├── MyChatClient.java │ │ │ │ │ ├── MyChatClientHandler.java │ │ │ │ │ ├── MyChatClientInitializer.java │ │ │ │ │ ├── MyChatServer.java │ │ │ │ │ ├── MyChatServerHandler.java │ │ │ │ │ └── MyChatServerInitializer.java │ │ │ ├── nio │ │ │ │ ├── NioClient.java │ │ │ │ ├── NioServer.java │ │ │ │ ├── NioTest1.java │ │ │ │ ├── NioTest10.java │ │ │ │ ├── NioTest11.java │ │ │ │ ├── NioTest12.java │ │ │ │ ├── NioTest13.java │ │ │ │ ├── NioTest2.java │ │ │ │ ├── NioTest3.java │ │ │ │ ├── NioTest4.java │ │ │ │ ├── NioTest5.java │ │ │ │ ├── NioTest6.java │ │ │ │ ├── NioTest7.java │ │ │ │ ├── NioTest8.java │ │ │ │ └── NioTest9.java │ │ │ ├── proto │ │ │ │ ├── MyRequest.java │ │ │ │ ├── MyRequestOrBuilder.java │ │ │ │ ├── MyResponse.java │ │ │ │ ├── MyResponseOrBuilder.java │ │ │ │ ├── StreamRequest.java │ │ │ │ ├── StreamRequestOrBuilder.java │ │ │ │ ├── StreamResponse.java │ │ │ │ ├── StreamResponseOrBuilder.java │ │ │ │ ├── StudentProto.java │ │ │ │ ├── StudentRequest.java │ │ │ │ ├── StudentRequestOrBuilder.java │ │ │ │ ├── StudentResponse.java │ │ │ │ ├── StudentResponseList.java │ │ │ │ ├── StudentResponseListOrBuilder.java │ │ │ │ ├── StudentResponseOrBuilder.java │ │ │ │ └── StudentServiceGrpc.java │ │ │ ├── protobuf │ │ │ │ ├── DataInfo.java │ │ │ │ └── ProtoBufTest.java │ │ │ └── thrift │ │ │ │ ├── PersonServiceImpl.java │ │ │ │ ├── ThriftClient.java │ │ │ │ └── ThriftServer.java │ │ └── shensiyuan │ │ │ └── zerocopy │ │ │ ├── NewIOClient.java │ │ │ ├── NewIOServer.java │ │ │ ├── OldIOClient.java │ │ │ └── OldIOServer.java │ └── thrift │ │ └── generated │ │ ├── DataException.java │ │ ├── Person.java │ │ └── PersonService.java ├── proto │ └── Student.proto └── resources │ └── log4j.properties ├── protobuf └── Person.proto ├── thrift └── data.thrift └── webapp └── test.html /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | build/ 3 | .gradle/ 4 | out/ -------------------------------------------------------------------------------- /NioTest10.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huiGod/netty_lecture/fb1145015fc25298edfd0e983bbb6e0001b28934/NioTest10.txt -------------------------------------------------------------------------------- /NioTest13_In.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huiGod/netty_lecture/fb1145015fc25298edfd0e983bbb6e0001b28934/NioTest13_In.txt -------------------------------------------------------------------------------- /NioTest13_Out.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huiGod/netty_lecture/fb1145015fc25298edfd0e983bbb6e0001b28934/NioTest13_Out.txt -------------------------------------------------------------------------------- /NioTest2.txt: -------------------------------------------------------------------------------- 1 | hello world welcome -------------------------------------------------------------------------------- /NioTest3.txt: -------------------------------------------------------------------------------- 1 | hello world welcome, nihao 2 | -------------------------------------------------------------------------------- /NioTest9.txt: -------------------------------------------------------------------------------- 1 | aelboworld 2 | welcome -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 精通并发与Netty 课程源码 2 | 3 | 课程源码位于src目录下,请将代码clone至本地,使用Intellij IDEA打开即可(代码构建使用了Gradle,请确保提前在本机安装好了Gradle) 4 | 5 | #### 版权所有@北京圣思园 -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | group 'com.shengsiyuan' 2 | version '1.0' 3 | 4 | apply plugin: 'java' 5 | apply plugin: 'com.google.protobuf' 6 | 7 | sourceCompatibility = 1.8 8 | targetCompatibility = 1.8 9 | 10 | repositories { 11 | mavenCentral() 12 | } 13 | 14 | dependencies { 15 | compile ( 16 | "io.netty:netty-all:4.1.15.Final", 17 | "com.google.protobuf:protobuf-java:3.3.1", 18 | "com.google.protobuf:protobuf-java-util:3.3.1", 19 | "org.apache.thrift:libthrift:0.10.0", 20 | "io.grpc:grpc-netty:1.4.0", 21 | "io.grpc:grpc-protobuf:1.4.0", 22 | "io.grpc:grpc-stub:1.4.0", 23 | "org.slf4j:slf4j-api:1.7.10", 24 | "org.slf4j:slf4j-log4j12:1.7.10" 25 | ) 26 | } 27 | 28 | buildscript { 29 | repositories { 30 | mavenCentral() 31 | } 32 | dependencies { 33 | classpath 'com.google.protobuf:protobuf-gradle-plugin:0.8.0' 34 | } 35 | } 36 | 37 | protobuf { 38 | protoc { 39 | artifact = "com.google.protobuf:protoc:3.2.0" 40 | } 41 | plugins { 42 | grpc { 43 | artifact = 'io.grpc:protoc-gen-grpc-java:1.4.0' 44 | } 45 | } 46 | 47 | generateProtoTasks.generatedFilesBaseDir = "src" 48 | 49 | generateProtoTasks { 50 | all()*.plugins { 51 | grpc { 52 | setOutputSubDir 'java' 53 | } 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /gen-py/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huiGod/netty_lecture/fb1145015fc25298edfd0e983bbb6e0001b28934/gen-py/__init__.py -------------------------------------------------------------------------------- /gen-py/py/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huiGod/netty_lecture/fb1145015fc25298edfd0e983bbb6e0001b28934/gen-py/py/__init__.py -------------------------------------------------------------------------------- /gen-py/py/thrift/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huiGod/netty_lecture/fb1145015fc25298edfd0e983bbb6e0001b28934/gen-py/py/thrift/__init__.py -------------------------------------------------------------------------------- /gen-py/py/thrift/generated/PersonService-remote: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # 3 | # Autogenerated by Thrift Compiler (0.10.0) 4 | # 5 | # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING 6 | # 7 | # options string: py 8 | # 9 | 10 | import sys 11 | import pprint 12 | if sys.version_info[0] > 2: 13 | from urllib.parse import urlparse 14 | else: 15 | from urlparse import urlparse 16 | from thrift.transport import TTransport, TSocket, TSSLSocket, THttpClient 17 | from thrift.protocol.TBinaryProtocol import TBinaryProtocol 18 | 19 | from py.thrift.generated import PersonService 20 | from py.thrift.generated.ttypes import * 21 | 22 | if len(sys.argv) <= 1 or sys.argv[1] == '--help': 23 | print('') 24 | print('Usage: ' + sys.argv[0] + ' [-h host[:port]] [-u url] [-f[ramed]] [-s[sl]] [-novalidate] [-ca_certs certs] [-keyfile keyfile] [-certfile certfile] function [arg1 [arg2...]]') 25 | print('') 26 | print('Functions:') 27 | print(' Person getPersonByUsername(String username)') 28 | print(' void savePerson(Person person)') 29 | print('') 30 | sys.exit(0) 31 | 32 | pp = pprint.PrettyPrinter(indent=2) 33 | host = 'localhost' 34 | port = 9090 35 | uri = '' 36 | framed = False 37 | ssl = False 38 | validate = True 39 | ca_certs = None 40 | keyfile = None 41 | certfile = None 42 | http = False 43 | argi = 1 44 | 45 | if sys.argv[argi] == '-h': 46 | parts = sys.argv[argi + 1].split(':') 47 | host = parts[0] 48 | if len(parts) > 1: 49 | port = int(parts[1]) 50 | argi += 2 51 | 52 | if sys.argv[argi] == '-u': 53 | url = urlparse(sys.argv[argi + 1]) 54 | parts = url[1].split(':') 55 | host = parts[0] 56 | if len(parts) > 1: 57 | port = int(parts[1]) 58 | else: 59 | port = 80 60 | uri = url[2] 61 | if url[4]: 62 | uri += '?%s' % url[4] 63 | http = True 64 | argi += 2 65 | 66 | if sys.argv[argi] == '-f' or sys.argv[argi] == '-framed': 67 | framed = True 68 | argi += 1 69 | 70 | if sys.argv[argi] == '-s' or sys.argv[argi] == '-ssl': 71 | ssl = True 72 | argi += 1 73 | 74 | if sys.argv[argi] == '-novalidate': 75 | validate = False 76 | argi += 1 77 | 78 | if sys.argv[argi] == '-ca_certs': 79 | ca_certs = sys.argv[argi+1] 80 | argi += 2 81 | 82 | if sys.argv[argi] == '-keyfile': 83 | keyfile = sys.argv[argi+1] 84 | argi += 2 85 | 86 | if sys.argv[argi] == '-certfile': 87 | certfile = sys.argv[argi+1] 88 | argi += 2 89 | 90 | cmd = sys.argv[argi] 91 | args = sys.argv[argi + 1:] 92 | 93 | if http: 94 | transport = THttpClient.THttpClient(host, port, uri) 95 | else: 96 | if ssl: 97 | socket = TSSLSocket.TSSLSocket(host, port, validate=validate, ca_certs=ca_certs, keyfile=keyfile, certfile=certfile) 98 | else: 99 | socket = TSocket.TSocket(host, port) 100 | if framed: 101 | transport = TTransport.TFramedTransport(socket) 102 | else: 103 | transport = TTransport.TBufferedTransport(socket) 104 | protocol = TBinaryProtocol(transport) 105 | client = PersonService.Client(protocol) 106 | transport.open() 107 | 108 | if cmd == 'getPersonByUsername': 109 | if len(args) != 1: 110 | print('getPersonByUsername requires 1 args') 111 | sys.exit(1) 112 | pp.pprint(client.getPersonByUsername(eval(args[0]),)) 113 | 114 | elif cmd == 'savePerson': 115 | if len(args) != 1: 116 | print('savePerson requires 1 args') 117 | sys.exit(1) 118 | pp.pprint(client.savePerson(eval(args[0]),)) 119 | 120 | else: 121 | print('Unrecognized method %s' % cmd) 122 | sys.exit(1) 123 | 124 | transport.close() 125 | -------------------------------------------------------------------------------- /gen-py/py/thrift/generated/PersonService.py: -------------------------------------------------------------------------------- 1 | # 2 | # Autogenerated by Thrift Compiler (0.10.0) 3 | # 4 | # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING 5 | # 6 | # options string: py 7 | # 8 | 9 | from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException 10 | from thrift.protocol.TProtocol import TProtocolException 11 | import sys 12 | import logging 13 | from .ttypes import * 14 | from thrift.Thrift import TProcessor 15 | from thrift.transport import TTransport 16 | 17 | 18 | class Iface(object): 19 | def getPersonByUsername(self, username): 20 | """ 21 | Parameters: 22 | - username 23 | """ 24 | pass 25 | 26 | def savePerson(self, person): 27 | """ 28 | Parameters: 29 | - person 30 | """ 31 | pass 32 | 33 | 34 | class Client(Iface): 35 | def __init__(self, iprot, oprot=None): 36 | self._iprot = self._oprot = iprot 37 | if oprot is not None: 38 | self._oprot = oprot 39 | self._seqid = 0 40 | 41 | def getPersonByUsername(self, username): 42 | """ 43 | Parameters: 44 | - username 45 | """ 46 | self.send_getPersonByUsername(username) 47 | return self.recv_getPersonByUsername() 48 | 49 | def send_getPersonByUsername(self, username): 50 | self._oprot.writeMessageBegin('getPersonByUsername', TMessageType.CALL, self._seqid) 51 | args = getPersonByUsername_args() 52 | args.username = username 53 | args.write(self._oprot) 54 | self._oprot.writeMessageEnd() 55 | self._oprot.trans.flush() 56 | 57 | def recv_getPersonByUsername(self): 58 | iprot = self._iprot 59 | (fname, mtype, rseqid) = iprot.readMessageBegin() 60 | if mtype == TMessageType.EXCEPTION: 61 | x = TApplicationException() 62 | x.read(iprot) 63 | iprot.readMessageEnd() 64 | raise x 65 | result = getPersonByUsername_result() 66 | result.read(iprot) 67 | iprot.readMessageEnd() 68 | if result.success is not None: 69 | return result.success 70 | if result.dataException is not None: 71 | raise result.dataException 72 | raise TApplicationException(TApplicationException.MISSING_RESULT, "getPersonByUsername failed: unknown result") 73 | 74 | def savePerson(self, person): 75 | """ 76 | Parameters: 77 | - person 78 | """ 79 | self.send_savePerson(person) 80 | self.recv_savePerson() 81 | 82 | def send_savePerson(self, person): 83 | self._oprot.writeMessageBegin('savePerson', TMessageType.CALL, self._seqid) 84 | args = savePerson_args() 85 | args.person = person 86 | args.write(self._oprot) 87 | self._oprot.writeMessageEnd() 88 | self._oprot.trans.flush() 89 | 90 | def recv_savePerson(self): 91 | iprot = self._iprot 92 | (fname, mtype, rseqid) = iprot.readMessageBegin() 93 | if mtype == TMessageType.EXCEPTION: 94 | x = TApplicationException() 95 | x.read(iprot) 96 | iprot.readMessageEnd() 97 | raise x 98 | result = savePerson_result() 99 | result.read(iprot) 100 | iprot.readMessageEnd() 101 | if result.dataException is not None: 102 | raise result.dataException 103 | return 104 | 105 | 106 | class Processor(Iface, TProcessor): 107 | def __init__(self, handler): 108 | self._handler = handler 109 | self._processMap = {} 110 | self._processMap["getPersonByUsername"] = Processor.process_getPersonByUsername 111 | self._processMap["savePerson"] = Processor.process_savePerson 112 | 113 | def process(self, iprot, oprot): 114 | (name, type, seqid) = iprot.readMessageBegin() 115 | if name not in self._processMap: 116 | iprot.skip(TType.STRUCT) 117 | iprot.readMessageEnd() 118 | x = TApplicationException(TApplicationException.UNKNOWN_METHOD, 'Unknown function %s' % (name)) 119 | oprot.writeMessageBegin(name, TMessageType.EXCEPTION, seqid) 120 | x.write(oprot) 121 | oprot.writeMessageEnd() 122 | oprot.trans.flush() 123 | return 124 | else: 125 | self._processMap[name](self, seqid, iprot, oprot) 126 | return True 127 | 128 | def process_getPersonByUsername(self, seqid, iprot, oprot): 129 | args = getPersonByUsername_args() 130 | args.read(iprot) 131 | iprot.readMessageEnd() 132 | result = getPersonByUsername_result() 133 | try: 134 | result.success = self._handler.getPersonByUsername(args.username) 135 | msg_type = TMessageType.REPLY 136 | except (TTransport.TTransportException, KeyboardInterrupt, SystemExit): 137 | raise 138 | except DataException as dataException: 139 | msg_type = TMessageType.REPLY 140 | result.dataException = dataException 141 | except Exception as ex: 142 | msg_type = TMessageType.EXCEPTION 143 | logging.exception(ex) 144 | result = TApplicationException(TApplicationException.INTERNAL_ERROR, 'Internal error') 145 | oprot.writeMessageBegin("getPersonByUsername", msg_type, seqid) 146 | result.write(oprot) 147 | oprot.writeMessageEnd() 148 | oprot.trans.flush() 149 | 150 | def process_savePerson(self, seqid, iprot, oprot): 151 | args = savePerson_args() 152 | args.read(iprot) 153 | iprot.readMessageEnd() 154 | result = savePerson_result() 155 | try: 156 | self._handler.savePerson(args.person) 157 | msg_type = TMessageType.REPLY 158 | except (TTransport.TTransportException, KeyboardInterrupt, SystemExit): 159 | raise 160 | except DataException as dataException: 161 | msg_type = TMessageType.REPLY 162 | result.dataException = dataException 163 | except Exception as ex: 164 | msg_type = TMessageType.EXCEPTION 165 | logging.exception(ex) 166 | result = TApplicationException(TApplicationException.INTERNAL_ERROR, 'Internal error') 167 | oprot.writeMessageBegin("savePerson", msg_type, seqid) 168 | result.write(oprot) 169 | oprot.writeMessageEnd() 170 | oprot.trans.flush() 171 | 172 | # HELPER FUNCTIONS AND STRUCTURES 173 | 174 | 175 | class getPersonByUsername_args(object): 176 | """ 177 | Attributes: 178 | - username 179 | """ 180 | 181 | thrift_spec = ( 182 | None, # 0 183 | (1, TType.STRING, 'username', 'UTF8', None, ), # 1 184 | ) 185 | 186 | def __init__(self, username=None,): 187 | self.username = username 188 | 189 | def read(self, iprot): 190 | if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: 191 | iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec)) 192 | return 193 | iprot.readStructBegin() 194 | while True: 195 | (fname, ftype, fid) = iprot.readFieldBegin() 196 | if ftype == TType.STOP: 197 | break 198 | if fid == 1: 199 | if ftype == TType.STRING: 200 | self.username = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() 201 | else: 202 | iprot.skip(ftype) 203 | else: 204 | iprot.skip(ftype) 205 | iprot.readFieldEnd() 206 | iprot.readStructEnd() 207 | 208 | def write(self, oprot): 209 | if oprot._fast_encode is not None and self.thrift_spec is not None: 210 | oprot.trans.write(oprot._fast_encode(self, (self.__class__, self.thrift_spec))) 211 | return 212 | oprot.writeStructBegin('getPersonByUsername_args') 213 | if self.username is not None: 214 | oprot.writeFieldBegin('username', TType.STRING, 1) 215 | oprot.writeString(self.username.encode('utf-8') if sys.version_info[0] == 2 else self.username) 216 | oprot.writeFieldEnd() 217 | oprot.writeFieldStop() 218 | oprot.writeStructEnd() 219 | 220 | def validate(self): 221 | if self.username is None: 222 | raise TProtocolException(message='Required field username is unset!') 223 | return 224 | 225 | def __repr__(self): 226 | L = ['%s=%r' % (key, value) 227 | for key, value in self.__dict__.items()] 228 | return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) 229 | 230 | def __eq__(self, other): 231 | return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ 232 | 233 | def __ne__(self, other): 234 | return not (self == other) 235 | 236 | 237 | class getPersonByUsername_result(object): 238 | """ 239 | Attributes: 240 | - success 241 | - dataException 242 | """ 243 | 244 | thrift_spec = ( 245 | (0, TType.STRUCT, 'success', (Person, Person.thrift_spec), None, ), # 0 246 | (1, TType.STRUCT, 'dataException', (DataException, DataException.thrift_spec), None, ), # 1 247 | ) 248 | 249 | def __init__(self, success=None, dataException=None,): 250 | self.success = success 251 | self.dataException = dataException 252 | 253 | def read(self, iprot): 254 | if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: 255 | iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec)) 256 | return 257 | iprot.readStructBegin() 258 | while True: 259 | (fname, ftype, fid) = iprot.readFieldBegin() 260 | if ftype == TType.STOP: 261 | break 262 | if fid == 0: 263 | if ftype == TType.STRUCT: 264 | self.success = Person() 265 | self.success.read(iprot) 266 | else: 267 | iprot.skip(ftype) 268 | elif fid == 1: 269 | if ftype == TType.STRUCT: 270 | self.dataException = DataException() 271 | self.dataException.read(iprot) 272 | else: 273 | iprot.skip(ftype) 274 | else: 275 | iprot.skip(ftype) 276 | iprot.readFieldEnd() 277 | iprot.readStructEnd() 278 | 279 | def write(self, oprot): 280 | if oprot._fast_encode is not None and self.thrift_spec is not None: 281 | oprot.trans.write(oprot._fast_encode(self, (self.__class__, self.thrift_spec))) 282 | return 283 | oprot.writeStructBegin('getPersonByUsername_result') 284 | if self.success is not None: 285 | oprot.writeFieldBegin('success', TType.STRUCT, 0) 286 | self.success.write(oprot) 287 | oprot.writeFieldEnd() 288 | if self.dataException is not None: 289 | oprot.writeFieldBegin('dataException', TType.STRUCT, 1) 290 | self.dataException.write(oprot) 291 | oprot.writeFieldEnd() 292 | oprot.writeFieldStop() 293 | oprot.writeStructEnd() 294 | 295 | def validate(self): 296 | return 297 | 298 | def __repr__(self): 299 | L = ['%s=%r' % (key, value) 300 | for key, value in self.__dict__.items()] 301 | return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) 302 | 303 | def __eq__(self, other): 304 | return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ 305 | 306 | def __ne__(self, other): 307 | return not (self == other) 308 | 309 | 310 | class savePerson_args(object): 311 | """ 312 | Attributes: 313 | - person 314 | """ 315 | 316 | thrift_spec = ( 317 | None, # 0 318 | (1, TType.STRUCT, 'person', (Person, Person.thrift_spec), None, ), # 1 319 | ) 320 | 321 | def __init__(self, person=None,): 322 | self.person = person 323 | 324 | def read(self, iprot): 325 | if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: 326 | iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec)) 327 | return 328 | iprot.readStructBegin() 329 | while True: 330 | (fname, ftype, fid) = iprot.readFieldBegin() 331 | if ftype == TType.STOP: 332 | break 333 | if fid == 1: 334 | if ftype == TType.STRUCT: 335 | self.person = Person() 336 | self.person.read(iprot) 337 | else: 338 | iprot.skip(ftype) 339 | else: 340 | iprot.skip(ftype) 341 | iprot.readFieldEnd() 342 | iprot.readStructEnd() 343 | 344 | def write(self, oprot): 345 | if oprot._fast_encode is not None and self.thrift_spec is not None: 346 | oprot.trans.write(oprot._fast_encode(self, (self.__class__, self.thrift_spec))) 347 | return 348 | oprot.writeStructBegin('savePerson_args') 349 | if self.person is not None: 350 | oprot.writeFieldBegin('person', TType.STRUCT, 1) 351 | self.person.write(oprot) 352 | oprot.writeFieldEnd() 353 | oprot.writeFieldStop() 354 | oprot.writeStructEnd() 355 | 356 | def validate(self): 357 | if self.person is None: 358 | raise TProtocolException(message='Required field person is unset!') 359 | return 360 | 361 | def __repr__(self): 362 | L = ['%s=%r' % (key, value) 363 | for key, value in self.__dict__.items()] 364 | return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) 365 | 366 | def __eq__(self, other): 367 | return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ 368 | 369 | def __ne__(self, other): 370 | return not (self == other) 371 | 372 | 373 | class savePerson_result(object): 374 | """ 375 | Attributes: 376 | - dataException 377 | """ 378 | 379 | thrift_spec = ( 380 | None, # 0 381 | (1, TType.STRUCT, 'dataException', (DataException, DataException.thrift_spec), None, ), # 1 382 | ) 383 | 384 | def __init__(self, dataException=None,): 385 | self.dataException = dataException 386 | 387 | def read(self, iprot): 388 | if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: 389 | iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec)) 390 | return 391 | iprot.readStructBegin() 392 | while True: 393 | (fname, ftype, fid) = iprot.readFieldBegin() 394 | if ftype == TType.STOP: 395 | break 396 | if fid == 1: 397 | if ftype == TType.STRUCT: 398 | self.dataException = DataException() 399 | self.dataException.read(iprot) 400 | else: 401 | iprot.skip(ftype) 402 | else: 403 | iprot.skip(ftype) 404 | iprot.readFieldEnd() 405 | iprot.readStructEnd() 406 | 407 | def write(self, oprot): 408 | if oprot._fast_encode is not None and self.thrift_spec is not None: 409 | oprot.trans.write(oprot._fast_encode(self, (self.__class__, self.thrift_spec))) 410 | return 411 | oprot.writeStructBegin('savePerson_result') 412 | if self.dataException is not None: 413 | oprot.writeFieldBegin('dataException', TType.STRUCT, 1) 414 | self.dataException.write(oprot) 415 | oprot.writeFieldEnd() 416 | oprot.writeFieldStop() 417 | oprot.writeStructEnd() 418 | 419 | def validate(self): 420 | return 421 | 422 | def __repr__(self): 423 | L = ['%s=%r' % (key, value) 424 | for key, value in self.__dict__.items()] 425 | return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) 426 | 427 | def __eq__(self, other): 428 | return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ 429 | 430 | def __ne__(self, other): 431 | return not (self == other) 432 | -------------------------------------------------------------------------------- /gen-py/py/thrift/generated/__init__.py: -------------------------------------------------------------------------------- 1 | __all__ = ['ttypes', 'constants', 'PersonService'] 2 | -------------------------------------------------------------------------------- /gen-py/py/thrift/generated/constants.py: -------------------------------------------------------------------------------- 1 | # 2 | # Autogenerated by Thrift Compiler (0.10.0) 3 | # 4 | # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING 5 | # 6 | # options string: py 7 | # 8 | 9 | from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException 10 | from thrift.protocol.TProtocol import TProtocolException 11 | import sys 12 | from .ttypes import * 13 | -------------------------------------------------------------------------------- /gen-py/py/thrift/generated/ttypes.py: -------------------------------------------------------------------------------- 1 | # 2 | # Autogenerated by Thrift Compiler (0.10.0) 3 | # 4 | # DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING 5 | # 6 | # options string: py 7 | # 8 | 9 | from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException 10 | from thrift.protocol.TProtocol import TProtocolException 11 | import sys 12 | 13 | from thrift.transport import TTransport 14 | 15 | 16 | class Person(object): 17 | """ 18 | Attributes: 19 | - username 20 | - age 21 | - married 22 | """ 23 | 24 | thrift_spec = ( 25 | None, # 0 26 | (1, TType.STRING, 'username', 'UTF8', None, ), # 1 27 | (2, TType.I32, 'age', None, None, ), # 2 28 | (3, TType.BOOL, 'married', None, None, ), # 3 29 | ) 30 | 31 | def __init__(self, username=None, age=None, married=None,): 32 | self.username = username 33 | self.age = age 34 | self.married = married 35 | 36 | def read(self, iprot): 37 | if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: 38 | iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec)) 39 | return 40 | iprot.readStructBegin() 41 | while True: 42 | (fname, ftype, fid) = iprot.readFieldBegin() 43 | if ftype == TType.STOP: 44 | break 45 | if fid == 1: 46 | if ftype == TType.STRING: 47 | self.username = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() 48 | else: 49 | iprot.skip(ftype) 50 | elif fid == 2: 51 | if ftype == TType.I32: 52 | self.age = iprot.readI32() 53 | else: 54 | iprot.skip(ftype) 55 | elif fid == 3: 56 | if ftype == TType.BOOL: 57 | self.married = iprot.readBool() 58 | else: 59 | iprot.skip(ftype) 60 | else: 61 | iprot.skip(ftype) 62 | iprot.readFieldEnd() 63 | iprot.readStructEnd() 64 | 65 | def write(self, oprot): 66 | if oprot._fast_encode is not None and self.thrift_spec is not None: 67 | oprot.trans.write(oprot._fast_encode(self, (self.__class__, self.thrift_spec))) 68 | return 69 | oprot.writeStructBegin('Person') 70 | if self.username is not None: 71 | oprot.writeFieldBegin('username', TType.STRING, 1) 72 | oprot.writeString(self.username.encode('utf-8') if sys.version_info[0] == 2 else self.username) 73 | oprot.writeFieldEnd() 74 | if self.age is not None: 75 | oprot.writeFieldBegin('age', TType.I32, 2) 76 | oprot.writeI32(self.age) 77 | oprot.writeFieldEnd() 78 | if self.married is not None: 79 | oprot.writeFieldBegin('married', TType.BOOL, 3) 80 | oprot.writeBool(self.married) 81 | oprot.writeFieldEnd() 82 | oprot.writeFieldStop() 83 | oprot.writeStructEnd() 84 | 85 | def validate(self): 86 | return 87 | 88 | def __repr__(self): 89 | L = ['%s=%r' % (key, value) 90 | for key, value in self.__dict__.items()] 91 | return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) 92 | 93 | def __eq__(self, other): 94 | return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ 95 | 96 | def __ne__(self, other): 97 | return not (self == other) 98 | 99 | 100 | class DataException(TException): 101 | """ 102 | Attributes: 103 | - message 104 | - callStack 105 | - date 106 | """ 107 | 108 | thrift_spec = ( 109 | None, # 0 110 | (1, TType.STRING, 'message', 'UTF8', None, ), # 1 111 | (2, TType.STRING, 'callStack', 'UTF8', None, ), # 2 112 | (3, TType.STRING, 'date', 'UTF8', None, ), # 3 113 | ) 114 | 115 | def __init__(self, message=None, callStack=None, date=None,): 116 | self.message = message 117 | self.callStack = callStack 118 | self.date = date 119 | 120 | def read(self, iprot): 121 | if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None: 122 | iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec)) 123 | return 124 | iprot.readStructBegin() 125 | while True: 126 | (fname, ftype, fid) = iprot.readFieldBegin() 127 | if ftype == TType.STOP: 128 | break 129 | if fid == 1: 130 | if ftype == TType.STRING: 131 | self.message = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() 132 | else: 133 | iprot.skip(ftype) 134 | elif fid == 2: 135 | if ftype == TType.STRING: 136 | self.callStack = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() 137 | else: 138 | iprot.skip(ftype) 139 | elif fid == 3: 140 | if ftype == TType.STRING: 141 | self.date = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString() 142 | else: 143 | iprot.skip(ftype) 144 | else: 145 | iprot.skip(ftype) 146 | iprot.readFieldEnd() 147 | iprot.readStructEnd() 148 | 149 | def write(self, oprot): 150 | if oprot._fast_encode is not None and self.thrift_spec is not None: 151 | oprot.trans.write(oprot._fast_encode(self, (self.__class__, self.thrift_spec))) 152 | return 153 | oprot.writeStructBegin('DataException') 154 | if self.message is not None: 155 | oprot.writeFieldBegin('message', TType.STRING, 1) 156 | oprot.writeString(self.message.encode('utf-8') if sys.version_info[0] == 2 else self.message) 157 | oprot.writeFieldEnd() 158 | if self.callStack is not None: 159 | oprot.writeFieldBegin('callStack', TType.STRING, 2) 160 | oprot.writeString(self.callStack.encode('utf-8') if sys.version_info[0] == 2 else self.callStack) 161 | oprot.writeFieldEnd() 162 | if self.date is not None: 163 | oprot.writeFieldBegin('date', TType.STRING, 3) 164 | oprot.writeString(self.date.encode('utf-8') if sys.version_info[0] == 2 else self.date) 165 | oprot.writeFieldEnd() 166 | oprot.writeFieldStop() 167 | oprot.writeStructEnd() 168 | 169 | def validate(self): 170 | return 171 | 172 | def __str__(self): 173 | return repr(self) 174 | 175 | def __repr__(self): 176 | L = ['%s=%r' % (key, value) 177 | for key, value in self.__dict__.items()] 178 | return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) 179 | 180 | def __eq__(self, other): 181 | return isinstance(other, self.__class__) and self.__dict__ == other.__dict__ 182 | 183 | def __ne__(self, other): 184 | return not (self == other) 185 | -------------------------------------------------------------------------------- /input.txt: -------------------------------------------------------------------------------- 1 | hello world 2 | welcome 3 | zhangsan 4 | lisi 5 | 王五 6 | 赵六 -------------------------------------------------------------------------------- /input2.txt: -------------------------------------------------------------------------------- 1 | hello world 2 | welcome 3 | zhangsan -------------------------------------------------------------------------------- /output.txt: -------------------------------------------------------------------------------- 1 | hello world 2 | welcome 3 | zhangsan 4 | lisi 5 | 王五 6 | 赵六 -------------------------------------------------------------------------------- /output2.txt: -------------------------------------------------------------------------------- 1 | hello world 2 | welcome 3 | zhangsan -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'netty_lecture' 2 | 3 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/decorator/Client.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.decorator; 2 | 3 | public class Client { 4 | 5 | public static void main(String[] args) { 6 | 7 | Component component = new ConcreteDecorator2(new ConcreteDecorator1( 8 | new ConcreteComponent())); 9 | 10 | component.doSomething(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/decorator/Component.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.decorator; 2 | 3 | public interface Component { 4 | 5 | void doSomething(); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/decorator/ConcreteComponent.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.decorator; 2 | 3 | public class ConcreteComponent implements Component { 4 | 5 | public void doSomething() { 6 | System.out.println("功能A"); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/decorator/ConcreteDecorator1.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.decorator; 2 | 3 | public class ConcreteDecorator1 extends Decorator { 4 | 5 | public ConcreteDecorator1(Component component) { 6 | super(component); 7 | } 8 | 9 | @Override 10 | public void doSomething() { 11 | super.doSomething(); 12 | this.doAnotherThing(); 13 | } 14 | 15 | private void doAnotherThing() { 16 | System.out.println("功能B"); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/decorator/ConcreteDecorator2.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.decorator; 2 | 3 | public class ConcreteDecorator2 extends Decorator { 4 | 5 | public ConcreteDecorator2(Component component) { 6 | super(component); 7 | } 8 | 9 | @Override 10 | public void doSomething() { 11 | super.doSomething(); 12 | this.doAnotherThing(); 13 | } 14 | 15 | private void doAnotherThing() { 16 | System.out.println("功能C"); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/decorator/Decorator.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.decorator; 2 | 3 | public class Decorator implements Component { 4 | 5 | private Component component; 6 | 7 | public Decorator(Component component) { 8 | this.component = component; 9 | } 10 | 11 | public void doSomething() { 12 | component.doSomething(); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/grpc/GrpcClient.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.grpc; 2 | 3 | 4 | import com.shengsiyuan.proto.*; 5 | import io.grpc.ManagedChannel; 6 | import io.grpc.ManagedChannelBuilder; 7 | import io.grpc.stub.StreamObserver; 8 | 9 | import java.time.LocalDateTime; 10 | import java.util.Iterator; 11 | 12 | public class GrpcClient { 13 | 14 | public static void main(String[] args) { 15 | ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost", 8899). 16 | usePlaintext(true).build(); 17 | StudentServiceGrpc.StudentServiceBlockingStub blockingStub = StudentServiceGrpc. 18 | newBlockingStub(managedChannel); 19 | StudentServiceGrpc.StudentServiceStub stub = StudentServiceGrpc.newStub(managedChannel); 20 | 21 | MyResponse myResponse = blockingStub. 22 | getRealNameByUsername(MyRequest.newBuilder().setUsername("zhangsan").build()); 23 | 24 | System.out.println(myResponse.getRealname()); 25 | 26 | // System.out.println("--------------------"); 27 | // 28 | // Iterator iter = blockingStub. 29 | // getStudentsByAge(StudentRequest.newBuilder().setAge(20).build()); 30 | // 31 | // while(iter.hasNext()) { 32 | // StudentResponse studentResponse = iter.next(); 33 | // 34 | // System.out.println(studentResponse.getName() + ", " + studentResponse.getAge() + ", " + studentResponse.getCity()); 35 | // } 36 | // 37 | // System.out.println("--------------------"); 38 | // 39 | // StreamObserver studentResponseListStreamObserver = new StreamObserver() { 40 | // @Override 41 | // public void onNext(StudentResponseList value) { 42 | // value.getStudentResponseList().forEach(studentResponse -> { 43 | // System.out.println(studentResponse.getName()); 44 | // System.out.println(studentResponse.getAge()); 45 | // System.out.println(studentResponse.getCity()); 46 | // System.out.println("******"); 47 | // }); 48 | // } 49 | // 50 | // @Override 51 | // public void onError(Throwable t) { 52 | // System.out.println(t.getMessage()); 53 | // } 54 | // 55 | // @Override 56 | // public void onCompleted() { 57 | // System.out.println("completed!"); 58 | // } 59 | // }; 60 | // 61 | // StreamObserver studentRequestStreamObserver = stub.getStudentsWrapperByAges(studentResponseListStreamObserver); 62 | // 63 | // studentRequestStreamObserver.onNext(StudentRequest.newBuilder().setAge(20).build()); 64 | // studentRequestStreamObserver.onNext(StudentRequest.newBuilder().setAge(30).build()); 65 | // studentRequestStreamObserver.onNext(StudentRequest.newBuilder().setAge(40).build()); 66 | // studentRequestStreamObserver.onNext(StudentRequest.newBuilder().setAge(50).build()); 67 | // 68 | // studentRequestStreamObserver.onCompleted(); 69 | // 70 | // StreamObserver requestStreamObserver = stub.biTalk(new StreamObserver() { 71 | // @Override 72 | // public void onNext(StreamResponse value) { 73 | // System.out.println(value.getResponseInfo()); 74 | // } 75 | // 76 | // @Override 77 | // public void onError(Throwable t) { 78 | // System.out.println(t.getMessage()); 79 | // } 80 | // 81 | // @Override 82 | // public void onCompleted() { 83 | // System.out.println("onCompleted"); 84 | // } 85 | // }); 86 | // 87 | // for(int i = 0; i < 10; ++i) { 88 | // requestStreamObserver.onNext(StreamRequest.newBuilder().setRequestInfo(LocalDateTime.now().toString()).build()); 89 | // 90 | // try { 91 | // Thread.sleep(1000); 92 | // } catch (InterruptedException e) { 93 | // e.printStackTrace(); 94 | // } 95 | // } 96 | // 97 | // 98 | // 99 | // try { 100 | // Thread.sleep(50000); 101 | // } catch (InterruptedException e) { 102 | // e.printStackTrace(); 103 | // } 104 | } 105 | } -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/grpc/GrpcServer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.grpc; 2 | 3 | 4 | import io.grpc.Server; 5 | import io.grpc.ServerBuilder; 6 | 7 | import java.io.IOException; 8 | 9 | public class GrpcServer { 10 | 11 | private Server server; 12 | 13 | private void start() throws IOException { 14 | this.server = ServerBuilder.forPort(8899).addService(new StudentServiceImpl()).build().start(); 15 | 16 | System.out.println("server started!"); 17 | 18 | Runtime.getRuntime().addShutdownHook(new Thread(() -> { 19 | System.out.println("关闭jvm"); 20 | GrpcServer.this.stop(); 21 | })); 22 | } 23 | 24 | private void stop() { 25 | if(null != this.server) { 26 | this.server.shutdown(); 27 | } 28 | } 29 | 30 | private void awaitTermination() throws InterruptedException { 31 | if(null != this.server) { 32 | this.server.awaitTermination(); 33 | } 34 | } 35 | 36 | public static void main(String[] args) throws IOException, InterruptedException { 37 | GrpcServer server = new GrpcServer(); 38 | 39 | server.start(); 40 | server.awaitTermination(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/grpc/StudentServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.grpc; 2 | 3 | 4 | import com.shengsiyuan.proto.*; 5 | import io.grpc.stub.StreamObserver; 6 | 7 | import java.util.UUID; 8 | 9 | public class StudentServiceImpl extends StudentServiceGrpc.StudentServiceImplBase { 10 | 11 | @Override 12 | public void getRealNameByUsername(MyRequest request, StreamObserver responseObserver) { 13 | System.out.println("接受到客户端信息: " + request.getUsername()); 14 | 15 | responseObserver.onNext(MyResponse.newBuilder().setRealname("张三").build()); 16 | responseObserver.onCompleted(); 17 | } 18 | 19 | @Override 20 | public void getStudentsByAge(StudentRequest request, StreamObserver responseObserver) { 21 | System.out.println("接受到客户端信息: " + request.getAge()); 22 | 23 | responseObserver.onNext(StudentResponse.newBuilder().setName("张三").setAge(20).setCity("北京").build()); 24 | responseObserver.onNext(StudentResponse.newBuilder().setName("李四").setAge(30).setCity("天津").build()); 25 | responseObserver.onNext(StudentResponse.newBuilder().setName("王五").setAge(40).setCity("成都").build()); 26 | responseObserver.onNext(StudentResponse.newBuilder().setName("赵六").setAge(50).setCity("深圳").build()); 27 | 28 | responseObserver.onCompleted(); 29 | } 30 | 31 | @Override 32 | public StreamObserver getStudentsWrapperByAges(StreamObserver responseObserver) { 33 | return new StreamObserver() { 34 | @Override 35 | public void onNext(StudentRequest value) { 36 | System.out.println("onNext: " + value.getAge()); 37 | } 38 | 39 | @Override 40 | public void onError(Throwable t) { 41 | System.out.println(t.getMessage()); 42 | } 43 | 44 | @Override 45 | public void onCompleted() { 46 | StudentResponse studentResponse = StudentResponse.newBuilder().setName("张三").setAge(20).setCity("西安").build(); 47 | StudentResponse studentResponse2 = StudentResponse.newBuilder().setName("李四").setAge(30).setCity("广州").build(); 48 | 49 | StudentResponseList studentResponseList = StudentResponseList.newBuilder(). 50 | addStudentResponse(studentResponse).addStudentResponse(studentResponse2).build(); 51 | 52 | responseObserver.onNext(studentResponseList); 53 | responseObserver.onCompleted(); 54 | } 55 | }; 56 | } 57 | 58 | @Override 59 | public StreamObserver biTalk(StreamObserver responseObserver) { 60 | return new StreamObserver() { 61 | @Override 62 | public void onNext(StreamRequest value) { 63 | System.out.println(value.getRequestInfo()); 64 | 65 | responseObserver.onNext(StreamResponse.newBuilder().setResponseInfo(UUID.randomUUID().toString()).build()); 66 | } 67 | 68 | @Override 69 | public void onError(Throwable t) { 70 | System.out.println(t.getMessage()); 71 | } 72 | 73 | @Override 74 | public void onCompleted() { 75 | responseObserver.onCompleted(); 76 | } 77 | }; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/bytebuf/AtomicUpdaterTest.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.bytebuf; 2 | 3 | import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; 4 | 5 | public class AtomicUpdaterTest { 6 | 7 | public static void main(String[] args) { 8 | // Person person = new Person(); 9 | // 10 | // for (int i = 0; i < 10; ++i) { 11 | // Thread thread = new Thread(() -> { 12 | // 13 | // try { 14 | // Thread.sleep(20); 15 | // } catch (InterruptedException e) { 16 | // e.printStackTrace(); 17 | // } 18 | // 19 | // System.out.println(person.age++); 20 | // }); 21 | // 22 | // thread.start(); 23 | // } 24 | 25 | Person person = new Person(); 26 | 27 | AtomicIntegerFieldUpdater atomicIntegerFieldUpdater = AtomicIntegerFieldUpdater. 28 | newUpdater(Person.class, "age"); 29 | 30 | for(int i = 0; i < 10; ++i) { 31 | Thread thread = new Thread(() -> { 32 | try { 33 | Thread.sleep(20); 34 | } catch (InterruptedException e) { 35 | e.printStackTrace(); 36 | } 37 | 38 | System.out.println(atomicIntegerFieldUpdater.getAndIncrement(person)); 39 | }); 40 | 41 | thread.start(); 42 | } 43 | } 44 | } 45 | 46 | class Person { 47 | volatile int age = 1; 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/bytebuf/ByteBufTest0.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.bytebuf; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | 6 | public class ByteBufTest0 { 7 | 8 | public static void main(String[] args) { 9 | ByteBuf buffer = Unpooled.buffer(10); 10 | 11 | for (int i = 0; i < 10; ++i) { 12 | buffer.writeByte(i); 13 | } 14 | 15 | // for (int i = 0; i < buffer.capacity(); ++i) { 16 | // System.out.println(buffer.getByte(i)); 17 | // } 18 | 19 | 20 | for(int i = 0; i < buffer.capacity(); ++i) { 21 | System.out.println(buffer.readByte()); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/bytebuf/ByteBufTest1.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.bytebuf; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.Unpooled; 5 | 6 | import java.nio.charset.Charset; 7 | 8 | public class ByteBufTest1 { 9 | 10 | public static void main(String[] args) { 11 | ByteBuf byteBuf = Unpooled.copiedBuffer("张hello world", Charset.forName("utf-8")); 12 | 13 | if (byteBuf.hasArray()) { 14 | byte[] content = byteBuf.array(); 15 | System.out.println(new String(content, Charset.forName("utf-8"))); 16 | 17 | System.out.println(byteBuf); 18 | 19 | System.out.println(byteBuf.arrayOffset()); 20 | System.out.println(byteBuf.readerIndex()); 21 | System.out.println(byteBuf.writerIndex()); 22 | System.out.println(byteBuf.capacity()); 23 | 24 | int length = byteBuf.readableBytes(); 25 | 26 | System.out.println(length); 27 | 28 | for(int i = 0; i < byteBuf.readableBytes(); ++i) { 29 | System.out.println((char)byteBuf.getByte(i)); 30 | } 31 | 32 | System.out.println(byteBuf.getCharSequence(0, 4, Charset.forName("utf-8"))); 33 | System.out.println(byteBuf.getCharSequence(4, 6, Charset.forName("utf-8"))); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/bytebuf/ByteBufTest2.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.bytebuf; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.buffer.CompositeByteBuf; 5 | import io.netty.buffer.Unpooled; 6 | 7 | import java.util.Iterator; 8 | 9 | public class ByteBufTest2 { 10 | 11 | public static void main(String[] args) { 12 | CompositeByteBuf compositeByteBuf = Unpooled.compositeBuffer(); 13 | 14 | ByteBuf heapBuf = Unpooled.buffer(10); 15 | ByteBuf directBuf = Unpooled.directBuffer(8); 16 | 17 | compositeByteBuf.addComponents(heapBuf, directBuf); 18 | // compositeByteBuf.removeComponent(0); 19 | 20 | Iterator iter = compositeByteBuf.iterator(); 21 | while (iter.hasNext()) { 22 | System.out.println(iter.next()); 23 | } 24 | 25 | compositeByteBuf.forEach(System.out::println); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/fifthexample/MyServer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.fifthexample; 2 | 3 | 4 | import io.netty.bootstrap.ServerBootstrap; 5 | import io.netty.channel.ChannelFuture; 6 | import io.netty.channel.EventLoopGroup; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.nio.NioServerSocketChannel; 9 | import io.netty.handler.logging.LogLevel; 10 | import io.netty.handler.logging.LoggingHandler; 11 | 12 | import java.net.InetSocketAddress; 13 | 14 | public class MyServer { 15 | 16 | public static void main(String[] args) throws Exception { 17 | EventLoopGroup bossGroup = new NioEventLoopGroup(); 18 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 19 | 20 | try { 21 | ServerBootstrap serverBootstrap = new ServerBootstrap(); 22 | serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class). 23 | handler(new LoggingHandler(LogLevel.INFO)). 24 | childHandler(new WebSocketChannelInitializer()); 25 | 26 | ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress(8899)).sync(); 27 | channelFuture.channel().closeFuture().sync(); 28 | } finally { 29 | bossGroup.shutdownGracefully(); 30 | workerGroup.shutdownGracefully(); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/fifthexample/TextWebSocketFrameHandler.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.fifthexample; 2 | 3 | 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.channel.SimpleChannelInboundHandler; 6 | import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; 7 | 8 | import java.time.LocalDateTime; 9 | 10 | public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler { 11 | 12 | @Override 13 | protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { 14 | System.out.println("收到消息: " + msg.text()); 15 | 16 | ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间: " + LocalDateTime.now())); 17 | } 18 | 19 | @Override 20 | public void handlerAdded(ChannelHandlerContext ctx) throws Exception { 21 | System.out.println("handlerAdded: " + ctx.channel().id().asLongText()); 22 | } 23 | 24 | @Override 25 | public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { 26 | System.out.println("handlerRemoved: " + ctx.channel().id().asLongText()); 27 | } 28 | 29 | @Override 30 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 31 | System.out.println("异常发生"); 32 | ctx.close(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/fifthexample/WebSocketChannelInitializer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.fifthexample; 2 | 3 | 4 | import io.netty.channel.ChannelInitializer; 5 | import io.netty.channel.ChannelPipeline; 6 | import io.netty.channel.socket.SocketChannel; 7 | import io.netty.handler.codec.http.HttpObjectAggregator; 8 | import io.netty.handler.codec.http.HttpServerCodec; 9 | import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler; 10 | import io.netty.handler.stream.ChunkedWriteHandler; 11 | 12 | 13 | public class WebSocketChannelInitializer extends ChannelInitializer { 14 | 15 | @Override 16 | protected void initChannel(SocketChannel ch) throws Exception { 17 | ChannelPipeline pipeline = ch.pipeline(); 18 | 19 | pipeline.addLast(new HttpServerCodec()); 20 | pipeline.addLast(new ChunkedWriteHandler()); 21 | pipeline.addLast(new HttpObjectAggregator(8192)); 22 | pipeline.addLast(new WebSocketServerProtocolHandler("/ws")); 23 | 24 | pipeline.addLast(new TextWebSocketFrameHandler()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/firstexample/TestHttpServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.firstexample; 2 | 3 | 4 | import io.netty.buffer.ByteBuf; 5 | import io.netty.buffer.Unpooled; 6 | import io.netty.channel.ChannelHandlerContext; 7 | import io.netty.channel.SimpleChannelInboundHandler; 8 | import io.netty.handler.codec.http.*; 9 | import io.netty.util.CharsetUtil; 10 | 11 | import java.net.URI; 12 | 13 | public class TestHttpServerHandler extends SimpleChannelInboundHandler { 14 | 15 | @Override 16 | protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { 17 | 18 | System.out.println(msg.getClass()); 19 | 20 | System.out.println(ctx.channel().remoteAddress()); 21 | Thread.sleep(8000); 22 | 23 | if (msg instanceof HttpRequest) { 24 | HttpRequest httpRequest = (HttpRequest)msg; 25 | 26 | System.out.println("请求方法名:" + httpRequest.method().name()); 27 | 28 | URI uri = new URI(httpRequest.uri()); 29 | if("/favicon.ico".equals(uri.getPath())) { 30 | System.out.println("请求favicon.ico"); 31 | return; 32 | } 33 | 34 | ByteBuf content = Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8); 35 | FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, 36 | HttpResponseStatus.OK, content); 37 | response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain"); 38 | response.headers().set(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes()); 39 | 40 | ctx.writeAndFlush(response); 41 | ctx.channel().close(); 42 | } 43 | } 44 | 45 | @Override 46 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 47 | System.out.println("channel active"); 48 | super.channelActive(ctx); 49 | } 50 | 51 | @Override 52 | public void channelRegistered(ChannelHandlerContext ctx) throws Exception { 53 | System.out.println("channel registered"); 54 | super.channelRegistered(ctx); 55 | } 56 | 57 | @Override 58 | public void handlerAdded(ChannelHandlerContext ctx) throws Exception { 59 | System.out.println("handler added"); 60 | super.handlerAdded(ctx); 61 | } 62 | 63 | @Override 64 | public void channelInactive(ChannelHandlerContext ctx) throws Exception { 65 | System.out.println("channel inactive"); 66 | super.channelInactive(ctx); 67 | } 68 | 69 | @Override 70 | public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { 71 | System.out.println("channel unregistered"); 72 | super.channelUnregistered(ctx); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/firstexample/TestServer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.firstexample; 2 | 3 | 4 | import io.netty.bootstrap.ServerBootstrap; 5 | import io.netty.channel.ChannelFuture; 6 | import io.netty.channel.EventLoopGroup; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.nio.NioServerSocketChannel; 9 | 10 | public class TestServer { 11 | 12 | public static void main(String[] args) throws Exception { 13 | EventLoopGroup bossGroup = new NioEventLoopGroup(); 14 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 15 | 16 | try { 17 | ServerBootstrap serverBootstrap = new ServerBootstrap(); 18 | serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class). 19 | childHandler(new TestServerInitializer()); 20 | 21 | ChannelFuture channelFuture = serverBootstrap.bind(8899).sync(); 22 | channelFuture.channel().closeFuture().sync(); 23 | } finally { 24 | bossGroup.shutdownGracefully(); 25 | workerGroup.shutdownGracefully(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/firstexample/TestServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.firstexample; 2 | 3 | 4 | import io.netty.channel.ChannelInitializer; 5 | import io.netty.channel.ChannelPipeline; 6 | import io.netty.channel.socket.SocketChannel; 7 | import io.netty.handler.codec.http.HttpServerCodec; 8 | 9 | 10 | public class TestServerInitializer extends ChannelInitializer{ 11 | 12 | @Override 13 | protected void initChannel(SocketChannel ch) throws Exception { 14 | ChannelPipeline pipeline = ch.pipeline(); 15 | 16 | pipeline.addLast("httpServerCodec", new HttpServerCodec()); 17 | pipeline.addLast("testHttpServerHandler", new TestHttpServerHandler()); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/fourthexample/MyServer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.fourthexample; 2 | 3 | 4 | import io.netty.bootstrap.ServerBootstrap; 5 | import io.netty.channel.ChannelFuture; 6 | import io.netty.channel.EventLoopGroup; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.nio.NioServerSocketChannel; 9 | import io.netty.handler.logging.LogLevel; 10 | import io.netty.handler.logging.LoggingHandler; 11 | 12 | public class MyServer { 13 | 14 | public static void main(String[] args) throws Exception { 15 | EventLoopGroup bossGroup = new NioEventLoopGroup(); 16 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 17 | 18 | try { 19 | ServerBootstrap serverBootstrap = new ServerBootstrap(); 20 | serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class). 21 | handler(new LoggingHandler(LogLevel.INFO)). 22 | childHandler(new MyServerInitializer()); 23 | 24 | ChannelFuture channelFuture = serverBootstrap.bind(8899).sync(); 25 | channelFuture.channel().closeFuture().sync(); 26 | } finally { 27 | bossGroup.shutdownGracefully(); 28 | workerGroup.shutdownGracefully(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/fourthexample/MyServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.fourthexample; 2 | 3 | 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.channel.ChannelInboundHandlerAdapter; 6 | import io.netty.handler.timeout.IdleStateEvent; 7 | 8 | public class MyServerHandler extends ChannelInboundHandlerAdapter { 9 | 10 | @Override 11 | public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { 12 | if(evt instanceof IdleStateEvent) { 13 | IdleStateEvent event = (IdleStateEvent)evt; 14 | 15 | String eventType = null; 16 | 17 | switch (event.state()) { 18 | case READER_IDLE: 19 | eventType = "读空闲"; 20 | break; 21 | case WRITER_IDLE: 22 | eventType = "写空闲"; 23 | break; 24 | case ALL_IDLE: 25 | eventType = "读写空闲"; 26 | break; 27 | } 28 | 29 | System.out.println(ctx.channel().remoteAddress() + "超时事件: " + eventType); 30 | ctx.channel().close(); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/fourthexample/MyServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.fourthexample; 2 | 3 | 4 | import io.netty.channel.ChannelInitializer; 5 | import io.netty.channel.ChannelPipeline; 6 | import io.netty.channel.socket.SocketChannel; 7 | import io.netty.handler.timeout.IdleStateHandler; 8 | 9 | import java.util.concurrent.TimeUnit; 10 | 11 | 12 | public class MyServerInitializer extends ChannelInitializer { 13 | 14 | @Override 15 | protected void initChannel(SocketChannel ch) throws Exception { 16 | ChannelPipeline pipeline = ch.pipeline(); 17 | 18 | pipeline.addLast(new IdleStateHandler(5, 7, 3, TimeUnit.SECONDS)); 19 | pipeline.addLast(new MyServerHandler()); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler/MyByteToLongDecoder.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.handler.codec.ByteToMessageDecoder; 6 | 7 | import java.util.List; 8 | 9 | public class MyByteToLongDecoder extends ByteToMessageDecoder { 10 | 11 | @Override 12 | protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { 13 | System.out.println("decode invoked!"); 14 | 15 | System.out.println(in.readableBytes()); 16 | 17 | if (in.readableBytes() >= 8) { 18 | out.add(in.readLong()); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler/MyByteToLongDecoder2.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.handler.codec.ReplayingDecoder; 6 | 7 | import java.util.List; 8 | 9 | public class MyByteToLongDecoder2 extends ReplayingDecoder { 10 | 11 | @Override 12 | protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { 13 | System.out.println("MyByteToLongDecoder2 decode invoked!"); 14 | 15 | out.add(in.readLong()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler/MyClient.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler; 2 | 3 | 4 | import io.netty.bootstrap.Bootstrap; 5 | import io.netty.channel.ChannelFuture; 6 | import io.netty.channel.EventLoopGroup; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.nio.NioSocketChannel; 9 | 10 | public class MyClient { 11 | 12 | public static void main(String[] args) throws Exception{ 13 | EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); 14 | 15 | try { 16 | Bootstrap bootstrap = new Bootstrap(); 17 | bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class). 18 | handler(new MyClientInitializer()); 19 | 20 | ChannelFuture channelFuture = bootstrap.connect("localhost", 8899).sync(); 21 | channelFuture.channel().closeFuture().sync(); 22 | } finally { 23 | eventLoopGroup.shutdownGracefully(); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler/MyClientHandler.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler; 2 | 3 | 4 | import io.netty.buffer.Unpooled; 5 | import io.netty.channel.ChannelHandlerContext; 6 | import io.netty.channel.SimpleChannelInboundHandler; 7 | 8 | import java.nio.charset.Charset; 9 | 10 | public class MyClientHandler extends SimpleChannelInboundHandler { 11 | 12 | @Override 13 | protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception { 14 | System.out.println(ctx.channel().remoteAddress()); 15 | System.out.println("client output: " + msg); 16 | } 17 | 18 | @Override 19 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 20 | ctx.writeAndFlush(123456L); 21 | 22 | // ctx.writeAndFlush(Unpooled.copiedBuffer("helloworld", Charset.forName("utf-8"))); 23 | } 24 | 25 | @Override 26 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 27 | cause.printStackTrace(); 28 | ctx.close(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler/MyClientInitializer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler; 2 | 3 | 4 | import io.netty.channel.ChannelInitializer; 5 | import io.netty.channel.ChannelPipeline; 6 | import io.netty.channel.socket.SocketChannel; 7 | 8 | 9 | public class MyClientInitializer extends ChannelInitializer { 10 | 11 | @Override 12 | protected void initChannel(SocketChannel ch) throws Exception { 13 | ChannelPipeline pipeline = ch.pipeline(); 14 | 15 | pipeline.addLast(new MyByteToLongDecoder2()); 16 | pipeline.addLast(new MyLongToByteEncoder()); 17 | pipeline.addLast(new MyClientHandler()); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler/MyLongToByteEncoder.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.handler.codec.MessageToByteEncoder; 6 | 7 | public class MyLongToByteEncoder extends MessageToByteEncoder{ 8 | 9 | @Override 10 | protected void encode(ChannelHandlerContext ctx, Long msg, ByteBuf out) throws Exception { 11 | System.out.println("encode invoked!"); 12 | 13 | System.out.println(msg); 14 | 15 | out.writeLong(msg); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler/MyLongToStringDecoder.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler; 2 | 3 | import io.netty.channel.ChannelHandlerContext; 4 | import io.netty.handler.codec.MessageToMessageDecoder; 5 | 6 | import java.util.List; 7 | 8 | public class MyLongToStringDecoder extends MessageToMessageDecoder { 9 | 10 | @Override 11 | protected void decode(ChannelHandlerContext ctx, Long msg, List out) throws Exception { 12 | System.out.println("MyLongToStringDecoder decode invoked!"); 13 | out.add(String.valueOf(msg)); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler/MyServer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.EventLoopGroup; 6 | import io.netty.channel.nio.NioEventLoopGroup; 7 | import io.netty.channel.socket.nio.NioServerSocketChannel; 8 | 9 | public class MyServer { 10 | 11 | public static void main(String[] args) throws Exception { 12 | EventLoopGroup bossGroup = new NioEventLoopGroup(1); 13 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 14 | 15 | try { 16 | ServerBootstrap serverBootstrap = new ServerBootstrap(); 17 | serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class). 18 | childHandler(new MyServerInitializer()); 19 | 20 | ChannelFuture channelFuture = serverBootstrap.bind(8899).sync(); 21 | channelFuture.channel().closeFuture().sync(); 22 | } finally { 23 | bossGroup.shutdownGracefully(); 24 | workerGroup.shutdownGracefully(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler/MyServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler; 2 | 3 | 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.channel.SimpleChannelInboundHandler; 6 | 7 | public class MyServerHandler extends SimpleChannelInboundHandler { 8 | 9 | @Override 10 | protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { 11 | System.out.println(ctx.channel().remoteAddress() + ", " + msg); 12 | 13 | ctx.writeAndFlush(654321L); 14 | } 15 | 16 | @Override 17 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 18 | cause.printStackTrace(); 19 | ctx.close(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler/MyServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler; 2 | 3 | 4 | import io.netty.channel.ChannelInitializer; 5 | import io.netty.channel.ChannelPipeline; 6 | import io.netty.channel.socket.SocketChannel; 7 | 8 | 9 | public class MyServerInitializer extends ChannelInitializer { 10 | 11 | @Override 12 | protected void initChannel(SocketChannel ch) throws Exception { 13 | ChannelPipeline pipeline = ch.pipeline(); 14 | 15 | pipeline.addLast(new MyByteToLongDecoder2()); 16 | pipeline.addLast(new MyLongToStringDecoder()); 17 | pipeline.addLast(new MyLongToByteEncoder()); 18 | pipeline.addLast(new MyServerHandler()); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler2/MyClient.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler2; 2 | 3 | 4 | import io.netty.bootstrap.Bootstrap; 5 | import io.netty.channel.ChannelFuture; 6 | import io.netty.channel.EventLoopGroup; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.nio.NioSocketChannel; 9 | 10 | public class MyClient { 11 | 12 | public static void main(String[] args) throws Exception{ 13 | EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); 14 | 15 | try { 16 | Bootstrap bootstrap = new Bootstrap(); 17 | bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class). 18 | handler(new MyClientInitializer()); 19 | 20 | ChannelFuture channelFuture = bootstrap.connect("localhost", 8899).sync(); 21 | channelFuture.channel().closeFuture().sync(); 22 | } finally { 23 | eventLoopGroup.shutdownGracefully(); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler2/MyClientHandler.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler2; 2 | 3 | 4 | import io.netty.buffer.ByteBuf; 5 | import io.netty.buffer.Unpooled; 6 | import io.netty.channel.ChannelHandlerContext; 7 | import io.netty.channel.SimpleChannelInboundHandler; 8 | 9 | import java.nio.charset.Charset; 10 | 11 | public class MyClientHandler extends SimpleChannelInboundHandler { 12 | 13 | private int count; 14 | 15 | @Override 16 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 17 | for (int i = 0; i < 10; ++i) { 18 | ByteBuf buffer = Unpooled.copiedBuffer("sent from client ", Charset.forName("utf-8")); 19 | ctx.writeAndFlush(buffer); 20 | } 21 | } 22 | 23 | @Override 24 | protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { 25 | byte[] buffer = new byte[msg.readableBytes()]; 26 | msg.readBytes(buffer); 27 | 28 | String message = new String(buffer, Charset.forName("utf-8")); 29 | 30 | System.out.println("客户端接收到的消息内容: " + message); 31 | System.out.println("客户端接收到的消息数量: " + (++this.count)); 32 | } 33 | 34 | @Override 35 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 36 | cause.printStackTrace(); 37 | ctx.close(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler2/MyClientInitializer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler2; 2 | 3 | 4 | import io.netty.channel.ChannelInitializer; 5 | import io.netty.channel.ChannelPipeline; 6 | import io.netty.channel.socket.SocketChannel; 7 | 8 | 9 | public class MyClientInitializer extends ChannelInitializer { 10 | 11 | @Override 12 | protected void initChannel(SocketChannel ch) throws Exception { 13 | ChannelPipeline pipeline = ch.pipeline(); 14 | 15 | pipeline.addLast(new MyClientHandler()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler2/MyServer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler2; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.EventLoopGroup; 6 | import io.netty.channel.nio.NioEventLoopGroup; 7 | import io.netty.channel.socket.nio.NioServerSocketChannel; 8 | 9 | public class MyServer { 10 | 11 | public static void main(String[] args) throws Exception { 12 | EventLoopGroup bossGroup = new NioEventLoopGroup(1); 13 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 14 | 15 | try { 16 | ServerBootstrap serverBootstrap = new ServerBootstrap(); 17 | serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class). 18 | childHandler(new MyServerInitializer()); 19 | 20 | ChannelFuture channelFuture = serverBootstrap.bind(8899).sync(); 21 | channelFuture.channel().closeFuture().sync(); 22 | } finally { 23 | bossGroup.shutdownGracefully(); 24 | workerGroup.shutdownGracefully(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler2/MyServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler2; 2 | 3 | 4 | import io.netty.buffer.ByteBuf; 5 | import io.netty.buffer.Unpooled; 6 | import io.netty.channel.ChannelHandlerContext; 7 | import io.netty.channel.SimpleChannelInboundHandler; 8 | 9 | import java.nio.charset.Charset; 10 | import java.util.UUID; 11 | 12 | public class MyServerHandler extends SimpleChannelInboundHandler { 13 | 14 | private int count; 15 | 16 | @Override 17 | protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception { 18 | byte[] buffer = new byte[msg.readableBytes()]; 19 | msg.readBytes(buffer); 20 | 21 | String message = new String(buffer, Charset.forName("utf-8")); 22 | 23 | System.out.println("服务端接收到的消息内容: " + message); 24 | System.out.println("服务端接收到的消息数量: " + (++this.count)); 25 | 26 | ByteBuf responseByteBuf = Unpooled.copiedBuffer(UUID.randomUUID().toString(), Charset.forName("utf-8")); 27 | ctx.writeAndFlush(responseByteBuf); 28 | } 29 | 30 | @Override 31 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 32 | cause.printStackTrace(); 33 | ctx.close(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler2/MyServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler2; 2 | 3 | 4 | import io.netty.channel.ChannelInitializer; 5 | import io.netty.channel.ChannelPipeline; 6 | import io.netty.channel.socket.SocketChannel; 7 | 8 | 9 | public class MyServerInitializer extends ChannelInitializer { 10 | 11 | @Override 12 | protected void initChannel(SocketChannel ch) throws Exception { 13 | System.out.println(this); 14 | 15 | ChannelPipeline pipeline = ch.pipeline(); 16 | 17 | pipeline.addLast(new MyServerHandler()); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler3/MyClient.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler3; 2 | 3 | 4 | import io.netty.bootstrap.Bootstrap; 5 | import io.netty.channel.ChannelFuture; 6 | import io.netty.channel.ChannelInitializer; 7 | import io.netty.channel.ChannelPipeline; 8 | import io.netty.channel.EventLoopGroup; 9 | import io.netty.channel.nio.NioEventLoopGroup; 10 | import io.netty.channel.socket.SocketChannel; 11 | import io.netty.channel.socket.nio.NioSocketChannel; 12 | 13 | public class MyClient { 14 | 15 | public static void main(String[] args) throws Exception { 16 | EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); 17 | 18 | try { 19 | Bootstrap bootstrap = new Bootstrap(); 20 | bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class). 21 | handler(new ChannelInitializer() { 22 | 23 | @Override 24 | protected void initChannel(SocketChannel ch) throws Exception { 25 | ChannelPipeline pipeline = ch.pipeline(); 26 | 27 | pipeline.addLast(new MyPersonDecoder()); 28 | pipeline.addLast(new MyPersonEncoder()); 29 | 30 | pipeline.addLast(new MyClientHandler()); 31 | } 32 | }); 33 | 34 | ChannelFuture channelFuture = bootstrap.connect("localhost", 8899).sync(); 35 | channelFuture.channel().closeFuture().sync(); 36 | } finally { 37 | eventLoopGroup.shutdownGracefully(); 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler3/MyClientHandler.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler3; 2 | 3 | import io.netty.channel.ChannelHandlerContext; 4 | import io.netty.channel.SimpleChannelInboundHandler; 5 | 6 | import java.nio.charset.Charset; 7 | 8 | public class MyClientHandler extends SimpleChannelInboundHandler { 9 | 10 | private int count; 11 | 12 | @Override 13 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 14 | for (int i = 0; i < 10; ++i) { 15 | String messageToBeSent = "sent from client "; 16 | byte[] content = messageToBeSent.getBytes(Charset.forName("utf-8")); 17 | int length = messageToBeSent.getBytes(Charset.forName("utf-8")).length; 18 | 19 | PersonProtocol personProtocol = new PersonProtocol(); 20 | personProtocol.setLength(length); 21 | personProtocol.setContent(content); 22 | 23 | ctx.writeAndFlush(personProtocol); 24 | } 25 | } 26 | 27 | @Override 28 | protected void channelRead0(ChannelHandlerContext ctx, PersonProtocol msg) throws Exception { 29 | int length = msg.getLength(); 30 | byte[] content = msg.getContent(); 31 | 32 | System.out.println("客户端接收到的消息: "); 33 | 34 | System.out.println("长度: " + length); 35 | System.out.println("内容:" + new String(content, Charset.forName("utf-8"))); 36 | 37 | System.out.println("客户端接受到的消息数量:" + (++this.count)); 38 | } 39 | 40 | @Override 41 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 42 | cause.printStackTrace(); 43 | ctx.close(); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler3/MyPersonDecoder.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler3; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.handler.codec.ReplayingDecoder; 6 | 7 | import java.util.List; 8 | 9 | public class MyPersonDecoder extends ReplayingDecoder { 10 | 11 | @Override 12 | protected void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { 13 | System.out.println("MyPersonDecoder decode invoked!"); 14 | 15 | int length = in.readInt(); 16 | 17 | byte[] content = new byte[length]; 18 | in.readBytes(content); 19 | 20 | PersonProtocol personProtocol = new PersonProtocol(); 21 | personProtocol.setLength(length); 22 | personProtocol.setContent(content); 23 | 24 | out.add(personProtocol); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler3/MyPersonEncoder.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler3; 2 | 3 | import io.netty.buffer.ByteBuf; 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.handler.codec.MessageToByteEncoder; 6 | 7 | public class MyPersonEncoder extends MessageToByteEncoder { 8 | 9 | @Override 10 | protected void encode(ChannelHandlerContext ctx, PersonProtocol msg, ByteBuf out) throws Exception { 11 | System.out.println("MyPersonEncoder encode invoked!"); 12 | 13 | out.writeInt(msg.getLength()); 14 | out.writeBytes(msg.getContent()); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler3/MyServer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler3; 2 | 3 | import io.netty.bootstrap.ServerBootstrap; 4 | import io.netty.channel.ChannelFuture; 5 | import io.netty.channel.EventLoopGroup; 6 | import io.netty.channel.nio.NioEventLoopGroup; 7 | import io.netty.channel.socket.nio.NioServerSocketChannel; 8 | 9 | public class MyServer { 10 | 11 | public static void main(String[] args) throws Exception { 12 | EventLoopGroup bossGroup = new NioEventLoopGroup(1); 13 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 14 | 15 | try { 16 | ServerBootstrap serverBootstrap = new ServerBootstrap(); 17 | serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class). 18 | childHandler(new MyServerInitializer()); 19 | 20 | ChannelFuture channelFuture = serverBootstrap.bind(8899).sync(); 21 | channelFuture.channel().closeFuture().sync(); 22 | } finally { 23 | bossGroup.shutdownGracefully(); 24 | workerGroup.shutdownGracefully(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler3/MyServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler3; 2 | 3 | import io.netty.channel.ChannelHandlerContext; 4 | import io.netty.channel.SimpleChannelInboundHandler; 5 | 6 | import java.nio.charset.Charset; 7 | import java.util.UUID; 8 | 9 | public class MyServerHandler extends SimpleChannelInboundHandler { 10 | 11 | private int count; 12 | 13 | @Override 14 | protected void channelRead0(ChannelHandlerContext ctx, PersonProtocol msg) throws Exception { 15 | int length = msg.getLength(); 16 | byte[] content = msg.getContent(); 17 | 18 | System.out.println("服务端接收到的数据:"); 19 | System.out.println("长度: " + length); 20 | System.out.println("内容:" + new String(content, Charset.forName("utf-8"))); 21 | 22 | System.out.println("服务端接收到的消息数量:" + (++this.count)); 23 | 24 | String responseMessage = UUID.randomUUID().toString(); 25 | int responseLength = responseMessage.getBytes("utf-8").length; 26 | byte[] responseContent = responseMessage.getBytes("utf-8"); 27 | 28 | PersonProtocol personProtocol = new PersonProtocol(); 29 | personProtocol.setLength(responseLength); 30 | personProtocol.setContent(responseContent); 31 | 32 | ctx.writeAndFlush(personProtocol); 33 | } 34 | 35 | @Override 36 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 37 | cause.printStackTrace(); 38 | ctx.close(); 39 | } 40 | } 41 | 42 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler3/MyServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler3; 2 | 3 | import io.netty.channel.ChannelInitializer; 4 | import io.netty.channel.ChannelPipeline; 5 | import io.netty.channel.socket.SocketChannel; 6 | 7 | 8 | public class MyServerInitializer extends ChannelInitializer { 9 | 10 | @Override 11 | protected void initChannel(SocketChannel ch) throws Exception { 12 | ChannelPipeline pipeline = ch.pipeline(); 13 | 14 | pipeline.addLast(new MyPersonDecoder()); 15 | pipeline.addLast(new MyPersonEncoder()); 16 | 17 | pipeline.addLast(new MyServerHandler()); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/handler3/PersonProtocol.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.handler3; 2 | 3 | public class PersonProtocol { 4 | 5 | private int length; 6 | 7 | private byte[] content; 8 | 9 | public int getLength() { 10 | return length; 11 | } 12 | 13 | public void setLength(int length) { 14 | this.length = length; 15 | } 16 | 17 | public byte[] getContent() { 18 | return content; 19 | } 20 | 21 | public void setContent(byte[] content) { 22 | this.content = content; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/secondexample/MyClient.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.secondexample; 2 | 3 | 4 | import io.netty.bootstrap.Bootstrap; 5 | import io.netty.channel.ChannelFuture; 6 | import io.netty.channel.EventLoopGroup; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.nio.NioSocketChannel; 9 | 10 | public class MyClient { 11 | 12 | public static void main(String[] args) throws Exception{ 13 | EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); 14 | 15 | try { 16 | Bootstrap bootstrap = new Bootstrap(); 17 | bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class). 18 | handler(new MyClientInitializer()); 19 | 20 | ChannelFuture channelFuture = bootstrap.connect("localhost", 8899).sync(); 21 | channelFuture.channel().closeFuture().sync(); 22 | } finally { 23 | eventLoopGroup.shutdownGracefully(); 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/secondexample/MyClientHandler.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.secondexample; 2 | 3 | 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.channel.SimpleChannelInboundHandler; 6 | 7 | import java.time.LocalDateTime; 8 | 9 | public class MyClientHandler extends SimpleChannelInboundHandler { 10 | 11 | @Override 12 | protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { 13 | System.out.println(ctx.channel().remoteAddress()); 14 | System.out.println("client output: " + msg); 15 | ctx.writeAndFlush("from client: " + LocalDateTime.now()); 16 | } 17 | 18 | @Override 19 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 20 | ctx.writeAndFlush("来自于客户端的问候!"); 21 | } 22 | 23 | @Override 24 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 25 | cause.printStackTrace(); 26 | ctx.close(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/secondexample/MyClientInitializer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.secondexample; 2 | 3 | 4 | import io.netty.channel.ChannelInitializer; 5 | import io.netty.channel.ChannelPipeline; 6 | import io.netty.channel.socket.SocketChannel; 7 | import io.netty.handler.codec.LengthFieldBasedFrameDecoder; 8 | import io.netty.handler.codec.LengthFieldPrepender; 9 | import io.netty.handler.codec.string.StringDecoder; 10 | import io.netty.handler.codec.string.StringEncoder; 11 | import io.netty.util.CharsetUtil; 12 | 13 | 14 | public class MyClientInitializer extends ChannelInitializer { 15 | 16 | @Override 17 | protected void initChannel(SocketChannel ch) throws Exception { 18 | ChannelPipeline pipeline = ch.pipeline(); 19 | 20 | pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)); 21 | pipeline.addLast(new LengthFieldPrepender(4)); 22 | pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8)); 23 | pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8)); 24 | pipeline.addLast(new MyClientHandler()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/secondexample/MyServer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.secondexample; 2 | 3 | 4 | import io.netty.bootstrap.ServerBootstrap; 5 | import io.netty.channel.ChannelFuture; 6 | import io.netty.channel.EventLoopGroup; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.nio.NioServerSocketChannel; 9 | import io.netty.handler.logging.LogLevel; 10 | import io.netty.handler.logging.LoggingHandler; 11 | 12 | public class MyServer { 13 | 14 | public static void main(String[] args) throws Exception { 15 | EventLoopGroup bossGroup = new NioEventLoopGroup(); 16 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 17 | 18 | try { 19 | ServerBootstrap serverBootstrap = new ServerBootstrap(); 20 | serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class). 21 | handler(new LoggingHandler(LogLevel.WARN)). 22 | childHandler(new MyServerInitializer()); 23 | 24 | ChannelFuture channelFuture = serverBootstrap.bind(8899).sync(); 25 | channelFuture.channel().closeFuture().sync(); 26 | } finally { 27 | bossGroup.shutdownGracefully(); 28 | workerGroup.shutdownGracefully(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/secondexample/MyServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.secondexample; 2 | 3 | 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.channel.SimpleChannelInboundHandler; 6 | 7 | import java.util.UUID; 8 | 9 | public class MyServerHandler extends SimpleChannelInboundHandler { 10 | 11 | @Override 12 | protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { 13 | System.out.println(ctx.channel().remoteAddress() + ", " + msg); 14 | ctx.channel().writeAndFlush("from server: " + UUID.randomUUID()); 15 | } 16 | 17 | @Override 18 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 19 | cause.printStackTrace(); 20 | ctx.close(); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/secondexample/MyServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.secondexample; 2 | 3 | 4 | import io.netty.channel.ChannelInitializer; 5 | import io.netty.channel.ChannelPipeline; 6 | import io.netty.channel.socket.SocketChannel; 7 | import io.netty.handler.codec.LengthFieldBasedFrameDecoder; 8 | import io.netty.handler.codec.LengthFieldPrepender; 9 | import io.netty.handler.codec.string.StringDecoder; 10 | import io.netty.handler.codec.string.StringEncoder; 11 | import io.netty.util.CharsetUtil; 12 | 13 | 14 | public class MyServerInitializer extends ChannelInitializer { 15 | 16 | @Override 17 | protected void initChannel(SocketChannel ch) throws Exception { 18 | ChannelPipeline pipeline = ch.pipeline(); 19 | 20 | pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)); 21 | pipeline.addLast(new LengthFieldPrepender(4)); 22 | pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8)); 23 | pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8)); 24 | pipeline.addLast(new MyServerHandler()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/sixthexample/TestClient.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.sixthexample; 2 | 3 | 4 | import io.netty.bootstrap.Bootstrap; 5 | import io.netty.channel.ChannelFuture; 6 | import io.netty.channel.EventLoopGroup; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.nio.NioSocketChannel; 9 | 10 | public class TestClient { 11 | 12 | public static void main(String[] args) throws Exception { 13 | EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); 14 | 15 | try { 16 | Bootstrap bootstrap = new Bootstrap(); 17 | bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class). 18 | handler(new TestClientInitializer()); 19 | 20 | ChannelFuture channelFuture = bootstrap.connect("localhost", 8899).sync(); 21 | channelFuture.channel().closeFuture().sync(); 22 | 23 | } finally { 24 | eventLoopGroup.shutdownGracefully(); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/sixthexample/TestClientHandler.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.sixthexample; 2 | 3 | 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.channel.SimpleChannelInboundHandler; 6 | 7 | import java.util.Random; 8 | 9 | public class TestClientHandler extends SimpleChannelInboundHandler { 10 | 11 | @Override 12 | protected void channelRead0(ChannelHandlerContext ctx, MyDataInfo.MyMessage msg) throws Exception { 13 | 14 | } 15 | 16 | @Override 17 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 18 | int randomInt = new Random().nextInt(3); 19 | 20 | MyDataInfo.MyMessage myMessage = null; 21 | 22 | if (0 == randomInt) { 23 | myMessage = MyDataInfo.MyMessage.newBuilder(). 24 | setDataType(MyDataInfo.MyMessage.DataType.PersonType). 25 | setPerson(MyDataInfo.Person.newBuilder(). 26 | setName("张三").setAge(20). 27 | setAddress("北京").build()). 28 | build(); 29 | } else if (1 == randomInt) { 30 | myMessage = MyDataInfo.MyMessage.newBuilder(). 31 | setDataType(MyDataInfo.MyMessage.DataType.DogType). 32 | setDog(MyDataInfo.Dog.newBuilder(). 33 | setName("一只狗").setAge(2). 34 | build()). 35 | build(); 36 | } else { 37 | myMessage = MyDataInfo.MyMessage.newBuilder(). 38 | setDataType(MyDataInfo.MyMessage.DataType.CatType). 39 | setCat(MyDataInfo.Cat.newBuilder(). 40 | setName("一只猫").setCity("上海"). 41 | build()). 42 | build(); 43 | } 44 | 45 | ctx.channel().writeAndFlush(myMessage); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/sixthexample/TestClientInitializer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.sixthexample; 2 | 3 | 4 | import io.netty.channel.ChannelInitializer; 5 | import io.netty.channel.ChannelPipeline; 6 | import io.netty.channel.socket.SocketChannel; 7 | import io.netty.handler.codec.protobuf.ProtobufDecoder; 8 | import io.netty.handler.codec.protobuf.ProtobufEncoder; 9 | import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; 10 | import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; 11 | 12 | 13 | public class TestClientInitializer extends ChannelInitializer{ 14 | 15 | @Override 16 | protected void initChannel(SocketChannel ch) throws Exception { 17 | ChannelPipeline pipeline = ch.pipeline(); 18 | 19 | pipeline.addLast(new ProtobufVarint32FrameDecoder()); 20 | pipeline.addLast(new ProtobufDecoder(MyDataInfo.MyMessage.getDefaultInstance())); 21 | pipeline.addLast(new ProtobufVarint32LengthFieldPrepender()); 22 | pipeline.addLast(new ProtobufEncoder()); 23 | 24 | pipeline.addLast(new TestClientHandler()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/sixthexample/TestServer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.sixthexample; 2 | 3 | 4 | import io.netty.bootstrap.ServerBootstrap; 5 | import io.netty.channel.ChannelFuture; 6 | import io.netty.channel.EventLoopGroup; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.nio.NioServerSocketChannel; 9 | import io.netty.handler.logging.LogLevel; 10 | import io.netty.handler.logging.LoggingHandler; 11 | 12 | public class TestServer { 13 | 14 | public static void main(String[] args) throws Exception { 15 | EventLoopGroup bossGroup = new NioEventLoopGroup(); 16 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 17 | 18 | try { 19 | ServerBootstrap serverBootstrap = new ServerBootstrap(); 20 | serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class). 21 | handler(new LoggingHandler(LogLevel.INFO)). 22 | childHandler(new TestServerInitializer()); 23 | 24 | ChannelFuture channelFuture = serverBootstrap.bind(8899).sync(); 25 | channelFuture.channel().closeFuture().sync(); 26 | } finally { 27 | bossGroup.shutdownGracefully(); 28 | workerGroup.shutdownGracefully(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/sixthexample/TestServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.sixthexample; 2 | 3 | 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.channel.SimpleChannelInboundHandler; 6 | 7 | public class TestServerHandler extends SimpleChannelInboundHandler { 8 | 9 | @Override 10 | protected void channelRead0(ChannelHandlerContext ctx, MyDataInfo.MyMessage msg) throws Exception { 11 | MyDataInfo.MyMessage.DataType dataType = msg.getDataType(); 12 | 13 | if (dataType == MyDataInfo.MyMessage.DataType.PersonType) { 14 | MyDataInfo.Person person = msg.getPerson(); 15 | 16 | System.out.println(person.getName()); 17 | System.out.println(person.getAge()); 18 | System.out.println(person.getAddress()); 19 | } else if (dataType == MyDataInfo.MyMessage.DataType.DogType) { 20 | MyDataInfo.Dog dog = msg.getDog(); 21 | 22 | System.out.println(dog.getName()); 23 | System.out.println(dog.getAge()); 24 | } else { 25 | MyDataInfo.Cat cat = msg.getCat(); 26 | 27 | System.out.println(cat.getName()); 28 | System.out.println(cat.getCity()); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/sixthexample/TestServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.sixthexample; 2 | 3 | 4 | import io.netty.channel.ChannelInitializer; 5 | import io.netty.channel.ChannelPipeline; 6 | import io.netty.channel.socket.SocketChannel; 7 | import io.netty.handler.codec.protobuf.ProtobufDecoder; 8 | import io.netty.handler.codec.protobuf.ProtobufEncoder; 9 | import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder; 10 | import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender; 11 | 12 | 13 | public class TestServerInitializer extends ChannelInitializer { 14 | 15 | @Override 16 | protected void initChannel(SocketChannel ch) throws Exception { 17 | ChannelPipeline pipeline = ch.pipeline(); 18 | 19 | pipeline.addLast(new ProtobufVarint32FrameDecoder()); 20 | pipeline.addLast(new ProtobufDecoder(MyDataInfo.MyMessage.getDefaultInstance())); 21 | pipeline.addLast(new ProtobufVarint32LengthFieldPrepender()); 22 | pipeline.addLast(new ProtobufEncoder()); 23 | 24 | pipeline.addLast(new TestServerHandler()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/test/Test.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.test; 2 | 3 | import io.netty.util.NettyRuntime; 4 | import io.netty.util.internal.SystemPropertyUtil; 5 | 6 | public class Test { 7 | 8 | public static void main(String[] args) { 9 | int result = Math.max(1, SystemPropertyUtil.getInt( 10 | "io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2)); 11 | 12 | System.out.println(result); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/thirdexample/MyChatClient.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.thirdexample; 2 | 3 | 4 | import io.netty.bootstrap.Bootstrap; 5 | import io.netty.channel.Channel; 6 | import io.netty.channel.EventLoopGroup; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.nio.NioSocketChannel; 9 | 10 | import java.io.BufferedReader; 11 | import java.io.InputStreamReader; 12 | 13 | public class MyChatClient { 14 | 15 | public static void main(String[] args) throws Exception { 16 | EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); 17 | 18 | try { 19 | Bootstrap bootstrap = new Bootstrap(); 20 | bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class). 21 | handler(new MyChatClientInitializer()); 22 | 23 | Channel channel = bootstrap.connect("localhost", 8899).sync().channel(); 24 | 25 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 26 | 27 | for (; ;) { 28 | channel.writeAndFlush(br.readLine() + "\r\n"); 29 | } 30 | 31 | } finally { 32 | eventLoopGroup.shutdownGracefully(); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/thirdexample/MyChatClientHandler.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.thirdexample; 2 | 3 | 4 | import io.netty.channel.ChannelHandlerContext; 5 | import io.netty.channel.SimpleChannelInboundHandler; 6 | 7 | public class MyChatClientHandler extends SimpleChannelInboundHandler{ 8 | 9 | @Override 10 | protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { 11 | System.out.println(msg); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/thirdexample/MyChatClientInitializer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.thirdexample; 2 | 3 | import io.netty.channel.ChannelInitializer; 4 | import io.netty.channel.ChannelPipeline; 5 | import io.netty.channel.socket.SocketChannel; 6 | import io.netty.handler.codec.DelimiterBasedFrameDecoder; 7 | import io.netty.handler.codec.Delimiters; 8 | import io.netty.handler.codec.string.StringDecoder; 9 | import io.netty.handler.codec.string.StringEncoder; 10 | import io.netty.util.CharsetUtil; 11 | 12 | 13 | public class MyChatClientInitializer extends ChannelInitializer { 14 | 15 | @Override 16 | protected void initChannel(SocketChannel ch) throws Exception { 17 | ChannelPipeline pipeline = ch.pipeline(); 18 | 19 | pipeline.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter())); 20 | pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8)); 21 | pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8)); 22 | pipeline.addLast(new MyChatClientHandler()); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/thirdexample/MyChatServer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.thirdexample; 2 | 3 | 4 | import io.netty.bootstrap.ServerBootstrap; 5 | import io.netty.channel.ChannelFuture; 6 | import io.netty.channel.EventLoopGroup; 7 | import io.netty.channel.nio.NioEventLoopGroup; 8 | import io.netty.channel.socket.nio.NioServerSocketChannel; 9 | 10 | public class MyChatServer { 11 | 12 | public static void main(String[] args) throws Exception { 13 | EventLoopGroup bossGroup = new NioEventLoopGroup(); 14 | EventLoopGroup workerGroup = new NioEventLoopGroup(); 15 | 16 | try { 17 | ServerBootstrap serverBootstrap = new ServerBootstrap(); 18 | serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class). 19 | childHandler(new MyChatServerInitializer()); 20 | 21 | ChannelFuture channelFuture = serverBootstrap.bind(8899).sync(); 22 | channelFuture.channel().closeFuture().sync(); 23 | } finally { 24 | bossGroup.shutdownGracefully(); 25 | workerGroup.shutdownGracefully(); 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/thirdexample/MyChatServerHandler.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.thirdexample; 2 | 3 | 4 | import io.netty.channel.Channel; 5 | import io.netty.channel.ChannelHandlerContext; 6 | import io.netty.channel.SimpleChannelInboundHandler; 7 | import io.netty.channel.group.ChannelGroup; 8 | import io.netty.channel.group.DefaultChannelGroup; 9 | import io.netty.util.concurrent.GlobalEventExecutor; 10 | 11 | public class MyChatServerHandler extends SimpleChannelInboundHandler{ 12 | 13 | private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); 14 | 15 | @Override 16 | protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { 17 | Channel channel = ctx.channel(); 18 | 19 | channelGroup.forEach(ch -> { 20 | if(channel != ch) { 21 | ch.writeAndFlush(channel.remoteAddress() + " 发送的消息:" + msg + "\n"); 22 | } else { 23 | ch.writeAndFlush("【自己】" + msg + "\n"); 24 | } 25 | }); 26 | } 27 | 28 | @Override 29 | public void handlerAdded(ChannelHandlerContext ctx) throws Exception { 30 | Channel channel = ctx.channel(); 31 | channelGroup.writeAndFlush("【服务器】- " + channel.remoteAddress() + " 加入\n"); 32 | channelGroup.add(channel); 33 | } 34 | 35 | @Override 36 | public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { 37 | Channel channel = ctx.channel(); 38 | channelGroup.writeAndFlush("【服务器】- " + channel.remoteAddress() + " 离开\n"); 39 | 40 | System.out.println(channelGroup.size()); 41 | } 42 | 43 | @Override 44 | public void channelActive(ChannelHandlerContext ctx) throws Exception { 45 | Channel channel = ctx.channel(); 46 | System.out.println(channel.remoteAddress() + " 上线"); 47 | } 48 | 49 | @Override 50 | public void channelInactive(ChannelHandlerContext ctx) throws Exception { 51 | Channel channel = ctx.channel(); 52 | System.out.println(channel.remoteAddress() + " 下线"); 53 | } 54 | 55 | @Override 56 | public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { 57 | cause.printStackTrace(); 58 | ctx.close(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/netty/thirdexample/MyChatServerInitializer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.netty.thirdexample; 2 | 3 | 4 | import io.netty.channel.ChannelInitializer; 5 | import io.netty.channel.ChannelPipeline; 6 | import io.netty.channel.socket.SocketChannel; 7 | import io.netty.handler.codec.DelimiterBasedFrameDecoder; 8 | import io.netty.handler.codec.Delimiters; 9 | import io.netty.handler.codec.string.StringDecoder; 10 | import io.netty.handler.codec.string.StringEncoder; 11 | import io.netty.util.CharsetUtil; 12 | 13 | 14 | public class MyChatServerInitializer extends ChannelInitializer { 15 | 16 | @Override 17 | protected void initChannel(SocketChannel ch) throws Exception { 18 | ChannelPipeline pipeline = ch.pipeline(); 19 | 20 | pipeline.addLast(new DelimiterBasedFrameDecoder(4096, Delimiters.lineDelimiter())); 21 | pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8)); 22 | pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8)); 23 | pipeline.addLast(new MyChatServerHandler()); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/nio/NioClient.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.nio; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | import java.net.InetSocketAddress; 7 | import java.nio.ByteBuffer; 8 | import java.nio.channels.SelectionKey; 9 | import java.nio.channels.Selector; 10 | import java.nio.channels.SocketChannel; 11 | import java.time.LocalDateTime; 12 | import java.util.Set; 13 | import java.util.concurrent.ExecutorService; 14 | import java.util.concurrent.Executors; 15 | 16 | public class NioClient { 17 | 18 | public static void main(String[] args) throws IOException { 19 | try { 20 | SocketChannel socketChannel = SocketChannel.open(); 21 | socketChannel.configureBlocking(false); 22 | 23 | Selector selector = Selector.open(); 24 | socketChannel.register(selector, SelectionKey.OP_CONNECT); 25 | socketChannel.connect(new InetSocketAddress("127.0.0.1", 8899)); 26 | 27 | while (true) { 28 | selector.select(); 29 | Set keySet = selector.selectedKeys(); 30 | 31 | for (SelectionKey selectionKey : keySet) { 32 | if (selectionKey.isConnectable()) { 33 | SocketChannel client = (SocketChannel) selectionKey.channel(); 34 | 35 | if (client.isConnectionPending()) { 36 | client.finishConnect(); 37 | 38 | ByteBuffer writeBuffer = ByteBuffer.allocate(1024); 39 | 40 | writeBuffer.put((LocalDateTime.now() + " 连接成功").getBytes()); 41 | writeBuffer.flip(); 42 | client.write(writeBuffer); 43 | 44 | ExecutorService executorService = Executors.newSingleThreadExecutor(Executors.defaultThreadFactory()); 45 | executorService.submit(() -> { 46 | while (true) { 47 | try { 48 | writeBuffer.clear(); 49 | InputStreamReader input = new InputStreamReader(System.in); 50 | BufferedReader br = new BufferedReader(input); 51 | 52 | String sendMessage = br.readLine(); 53 | 54 | writeBuffer.put(sendMessage.getBytes()); 55 | writeBuffer.flip(); 56 | client.write(writeBuffer); 57 | } catch (Exception ex) { 58 | ex.printStackTrace(); 59 | } 60 | } 61 | }); 62 | } 63 | 64 | client.register(selector, SelectionKey.OP_READ); 65 | } else if (selectionKey.isReadable()) { 66 | SocketChannel client = (SocketChannel) selectionKey.channel(); 67 | 68 | ByteBuffer readBuffer = ByteBuffer.allocate(1024); 69 | 70 | int count = client.read(readBuffer); 71 | 72 | if (count > 0) { 73 | String receivedMessage = new String(readBuffer.array(), 0, count); 74 | System.out.println(receivedMessage); 75 | } 76 | } 77 | } 78 | 79 | keySet.clear(); 80 | } 81 | } catch (Exception ex) { 82 | ex.printStackTrace(); 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/nio/NioServer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.nio; 2 | 3 | import java.io.IOException; 4 | import java.net.InetSocketAddress; 5 | import java.net.ServerSocket; 6 | import java.nio.ByteBuffer; 7 | import java.nio.channels.SelectionKey; 8 | import java.nio.channels.Selector; 9 | import java.nio.channels.ServerSocketChannel; 10 | import java.nio.channels.SocketChannel; 11 | import java.nio.charset.Charset; 12 | import java.util.HashMap; 13 | import java.util.Map; 14 | import java.util.Set; 15 | import java.util.UUID; 16 | 17 | public class NioServer { 18 | 19 | private static Map clientMap = new HashMap(); 20 | 21 | public static void main(String[] args) throws IOException { 22 | ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); 23 | serverSocketChannel.configureBlocking(false); 24 | ServerSocket serverSocket = serverSocketChannel.socket(); 25 | serverSocket.bind(new InetSocketAddress(8899)); 26 | 27 | Selector selector = Selector.open(); 28 | serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); 29 | 30 | while (true) { 31 | try { 32 | selector.select(); 33 | 34 | Set selectionKeys = selector.selectedKeys(); 35 | 36 | selectionKeys.forEach(selectionKey -> { 37 | final SocketChannel client; 38 | 39 | try { 40 | if (selectionKey.isAcceptable()) { 41 | ServerSocketChannel server = (ServerSocketChannel) selectionKey.channel(); 42 | client = server.accept(); 43 | client.configureBlocking(false); 44 | client.register(selector, SelectionKey.OP_READ); 45 | 46 | String key = "【" + UUID.randomUUID().toString() + "】"; 47 | 48 | clientMap.put(key, client); 49 | } else if (selectionKey.isReadable()) { 50 | client = (SocketChannel) selectionKey.channel(); 51 | ByteBuffer readBuffer = ByteBuffer.allocate(1024); 52 | 53 | int count = client.read(readBuffer); 54 | 55 | if (count > 0) { 56 | readBuffer.flip(); 57 | 58 | Charset charset = Charset.forName("utf-8"); 59 | String receivedMessage = String.valueOf(charset.decode(readBuffer).array()); 60 | 61 | System.out.println(client + ": " + receivedMessage); 62 | 63 | String senderKey = null; 64 | 65 | for (Map.Entry entry : clientMap.entrySet()) { 66 | if (client == entry.getValue()) { 67 | senderKey = entry.getKey(); 68 | break; 69 | } 70 | } 71 | 72 | for (Map.Entry entry : clientMap.entrySet()) { 73 | SocketChannel value = entry.getValue(); 74 | 75 | ByteBuffer writeBuffer = ByteBuffer.allocate(1024); 76 | 77 | writeBuffer.put((senderKey + ": " + receivedMessage).getBytes()); 78 | writeBuffer.flip(); 79 | 80 | value.write(writeBuffer); 81 | } 82 | } 83 | } 84 | } catch (Exception ex) { 85 | ex.printStackTrace(); 86 | } 87 | }); 88 | 89 | selectionKeys.clear(); 90 | } catch (Exception ex) { 91 | ex.printStackTrace(); 92 | } 93 | } 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/nio/NioTest1.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.nio; 2 | 3 | 4 | import java.nio.IntBuffer; 5 | import java.security.SecureRandom; 6 | 7 | public class NioTest1 { 8 | 9 | public static void main(String[] args) { 10 | IntBuffer buffer = IntBuffer.allocate(10); 11 | 12 | System.out.println("capacity: " + buffer.capacity()); 13 | 14 | for(int i = 0; i < 5; ++i) { 15 | int randomNumber = new SecureRandom().nextInt(20); 16 | buffer.put(randomNumber); 17 | } 18 | 19 | System.out.println("before flip limit: " + buffer.limit()); 20 | 21 | buffer.flip(); 22 | 23 | System.out.println("after flip limit: " + buffer.limit()); 24 | 25 | System.out.println("enter while loop"); 26 | 27 | while(buffer.hasRemaining()) { 28 | System.out.println("position: " + buffer.position()); 29 | System.out.println("limit: " + buffer.limit()); 30 | System.out.println("capacity: " + buffer.capacity()); 31 | 32 | System.out.println(buffer.get()); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/nio/NioTest10.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.nio; 2 | 3 | 4 | import java.io.RandomAccessFile; 5 | import java.nio.channels.FileChannel; 6 | import java.nio.channels.FileLock; 7 | 8 | public class NioTest10 { 9 | 10 | public static void main(String[] args) throws Exception{ 11 | RandomAccessFile randomAccessFile = new RandomAccessFile("NioTest10.txt", "rw"); 12 | FileChannel fileChannel = randomAccessFile.getChannel(); 13 | 14 | FileLock fileLock = fileChannel.lock(3, 6, true); 15 | 16 | System.out.println("valid: " + fileLock.isValid()); 17 | System.out.println("lock type: " + fileLock.isShared()); 18 | 19 | fileLock.release(); 20 | 21 | randomAccessFile.close(); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/nio/NioTest11.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.nio; 2 | 3 | import java.net.InetSocketAddress; 4 | import java.nio.ByteBuffer; 5 | import java.nio.channels.ServerSocketChannel; 6 | import java.nio.channels.SocketChannel; 7 | import java.util.Arrays; 8 | 9 | /** 10 | * 关于Buffer的Scattering与Gathering 11 | */ 12 | 13 | public class NioTest11 { 14 | 15 | public static void main(String[] args) throws Exception { 16 | ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); 17 | InetSocketAddress address = new InetSocketAddress(8899); 18 | serverSocketChannel.socket().bind(address); 19 | 20 | int messageLength = 2 + 3 + 4; 21 | 22 | ByteBuffer[] buffers = new ByteBuffer[3]; 23 | 24 | buffers[0] = ByteBuffer.allocate(2); 25 | buffers[1] = ByteBuffer.allocate(3); 26 | buffers[2] = ByteBuffer.allocate(4); 27 | 28 | SocketChannel socketChannel = serverSocketChannel.accept(); 29 | 30 | while (true) { 31 | int bytesRead = 0; 32 | 33 | while (bytesRead < messageLength) { 34 | long r = socketChannel.read(buffers); 35 | bytesRead += r; 36 | 37 | System.out.println("bytesRead: " + bytesRead); 38 | 39 | Arrays.asList(buffers).stream(). 40 | map(buffer -> "position: " + buffer.position() + ", limit: " + buffer.limit()). 41 | forEach(System.out::println); 42 | } 43 | 44 | Arrays.asList(buffers).forEach(buffer -> { 45 | buffer.flip(); 46 | }); 47 | 48 | long bytesWritten = 0; 49 | while (bytesWritten < messageLength) { 50 | long r = socketChannel.write(buffers); 51 | bytesWritten += r; 52 | } 53 | 54 | Arrays.asList(buffers).forEach(buffer -> { 55 | buffer.clear(); 56 | }); 57 | 58 | System.out.println("bytesRead: " + bytesRead + ", bytesWritten: " + bytesWritten + ", messageLength: " + messageLength); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/nio/NioTest12.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.nio; 2 | 3 | 4 | import java.net.InetSocketAddress; 5 | import java.net.ServerSocket; 6 | import java.nio.ByteBuffer; 7 | import java.nio.channels.SelectionKey; 8 | import java.nio.channels.Selector; 9 | import java.nio.channels.ServerSocketChannel; 10 | import java.nio.channels.SocketChannel; 11 | import java.util.Iterator; 12 | import java.util.Set; 13 | 14 | public class NioTest12 { 15 | 16 | public static void main(String[] args) throws Exception { 17 | int[] ports = new int[5]; 18 | 19 | ports[0] = 5000; 20 | ports[1] = 5001; 21 | ports[2] = 5002; 22 | ports[3] = 5003; 23 | ports[4] = 5004; 24 | 25 | Selector selector = Selector.open(); 26 | 27 | for (int i = 0; i < ports.length; ++i) { 28 | ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); 29 | serverSocketChannel.configureBlocking(false); 30 | ServerSocket serverSocket = serverSocketChannel.socket(); 31 | InetSocketAddress address = new InetSocketAddress(ports[i]); 32 | serverSocket.bind(address); 33 | 34 | serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); 35 | 36 | System.out.println("监听端口: " + ports[i]); 37 | } 38 | 39 | while (true) { 40 | int numbers = selector.select(); 41 | System.out.println("numbers: " + numbers); 42 | 43 | Set selectionKeys = selector.selectedKeys(); 44 | 45 | System.out.println("selectedKeys: " + selectionKeys); 46 | 47 | Iterator iter = selectionKeys.iterator(); 48 | 49 | while (iter.hasNext()) { 50 | SelectionKey selectionKey = iter.next(); 51 | 52 | if (selectionKey.isAcceptable()) { 53 | ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel(); 54 | SocketChannel socketChannel = serverSocketChannel.accept(); 55 | socketChannel.configureBlocking(false); 56 | 57 | socketChannel.register(selector, SelectionKey.OP_READ); 58 | 59 | iter.remove(); 60 | 61 | System.out.println("获得客户端连接: " + socketChannel); 62 | } else if (selectionKey.isReadable()) { 63 | SocketChannel socketChannel = (SocketChannel) selectionKey.channel(); 64 | 65 | int bytesRead = 0; 66 | 67 | while (true) { 68 | ByteBuffer byteBuffer = ByteBuffer.allocate(512); 69 | 70 | byteBuffer.clear(); 71 | 72 | int read = socketChannel.read(byteBuffer); 73 | 74 | if (read <= 0) { 75 | break; 76 | } 77 | 78 | byteBuffer.flip(); 79 | 80 | socketChannel.write(byteBuffer); 81 | 82 | bytesRead += read; 83 | } 84 | 85 | System.out.println("读取: " + bytesRead + ",来自于: " + socketChannel); 86 | 87 | iter.remove(); 88 | } 89 | } 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/nio/NioTest13.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.nio; 2 | 3 | import java.io.File; 4 | import java.io.RandomAccessFile; 5 | import java.nio.ByteBuffer; 6 | import java.nio.CharBuffer; 7 | import java.nio.MappedByteBuffer; 8 | import java.nio.channels.FileChannel; 9 | import java.nio.charset.Charset; 10 | import java.nio.charset.CharsetDecoder; 11 | import java.nio.charset.CharsetEncoder; 12 | 13 | public class NioTest13 { 14 | 15 | public static void main(String[] args) throws Exception{ 16 | String inputFile = "NioTest13_In.txt"; 17 | String outputFile = "NioTest13_Out.txt"; 18 | 19 | RandomAccessFile inputRandomAccessFile = new RandomAccessFile(inputFile, "r"); 20 | RandomAccessFile outputRandomAccessFile = new RandomAccessFile(outputFile, "rw"); 21 | 22 | long inputLength = new File(inputFile).length(); 23 | 24 | FileChannel inputFileChannel = inputRandomAccessFile.getChannel(); 25 | FileChannel outputFileChannel = outputRandomAccessFile.getChannel(); 26 | 27 | MappedByteBuffer inputData = inputFileChannel.map(FileChannel.MapMode.READ_ONLY, 0, inputLength); 28 | 29 | System.out.println("============="); 30 | 31 | Charset.availableCharsets().forEach((k, v) -> { 32 | System.out.println(k + ", " + v); 33 | }); 34 | 35 | System.out.println("============="); 36 | 37 | Charset charset = Charset.forName("iso-8859-1"); 38 | CharsetDecoder decoder = charset.newDecoder(); 39 | CharsetEncoder encoder = charset.newEncoder(); 40 | 41 | CharBuffer charBuffer = decoder.decode(inputData); 42 | 43 | // System.out.println(charBuffer.get(12)); 44 | 45 | ByteBuffer outputData = encoder.encode(charBuffer); 46 | 47 | // ByteBuffer outputData = Charset.forName("utf-8").encode(charBuffer); 48 | 49 | outputFileChannel.write(outputData); 50 | 51 | inputRandomAccessFile.close(); 52 | outputRandomAccessFile.close(); 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/nio/NioTest2.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.nio; 2 | 3 | 4 | import java.io.FileInputStream; 5 | import java.nio.ByteBuffer; 6 | import java.nio.channels.FileChannel; 7 | 8 | public class NioTest2 { 9 | 10 | public static void main(String[] args) throws Exception { 11 | 12 | FileInputStream fileInputStream = new FileInputStream("NioTest2.txt"); 13 | FileChannel fileChannel = fileInputStream.getChannel(); 14 | 15 | ByteBuffer byteBuffer = ByteBuffer.allocate(512); 16 | fileChannel.read(byteBuffer); 17 | 18 | byteBuffer.flip(); 19 | 20 | while(byteBuffer.remaining() > 0) { 21 | byte b = byteBuffer.get(); 22 | System.out.println("Character: " + (char)b); 23 | } 24 | 25 | fileInputStream.close(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/nio/NioTest3.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.nio; 2 | 3 | 4 | import java.io.FileOutputStream; 5 | import java.nio.ByteBuffer; 6 | import java.nio.channels.FileChannel; 7 | 8 | public class NioTest3 { 9 | 10 | public static void main(String[] args) throws Exception{ 11 | FileOutputStream fileOutputStream = new FileOutputStream("NioTest3.txt"); 12 | FileChannel fileChannel = fileOutputStream.getChannel(); 13 | 14 | ByteBuffer byteBuffer = ByteBuffer.allocate(512); 15 | 16 | byte[] messages = "hello world welcome, nihao".getBytes(); 17 | 18 | for(int i = 0; i < messages.length; ++i) { 19 | byteBuffer.put(messages[i]); 20 | } 21 | 22 | byteBuffer.flip(); 23 | 24 | fileChannel.write(byteBuffer); 25 | 26 | fileOutputStream.close(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/nio/NioTest4.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.nio; 2 | 3 | 4 | import java.io.FileInputStream; 5 | import java.io.FileOutputStream; 6 | import java.nio.ByteBuffer; 7 | import java.nio.channels.FileChannel; 8 | 9 | public class NioTest4 { 10 | 11 | public static void main(String[] args) throws Exception { 12 | FileInputStream inputStream = new FileInputStream("input.txt"); 13 | FileOutputStream outputStream = new FileOutputStream("output.txt"); 14 | 15 | FileChannel inputChannel = inputStream.getChannel(); 16 | FileChannel outputChannel = outputStream.getChannel(); 17 | 18 | ByteBuffer buffer = ByteBuffer.allocate(512); 19 | 20 | while(true) { 21 | // buffer.clear(); // 如果注释掉该行代码会发生什么情况? 22 | 23 | int read = inputChannel.read(buffer); 24 | 25 | System.out.println("read: " + read); 26 | 27 | if(-1 == read) { 28 | break; 29 | } 30 | 31 | buffer.flip(); 32 | 33 | outputChannel.write(buffer); 34 | } 35 | 36 | inputChannel.close(); 37 | outputChannel.close(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/nio/NioTest5.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.nio; 2 | 3 | 4 | import java.nio.ByteBuffer; 5 | 6 | /** 7 | * ByteBuffer类型化的put与get方法 8 | */ 9 | public class NioTest5 { 10 | 11 | public static void main(String[] args) { 12 | ByteBuffer buffer = ByteBuffer.allocate(64); 13 | 14 | buffer.putInt(15); 15 | buffer.putLong(500000000L); 16 | buffer.putDouble(14.123456); 17 | buffer.putChar('你'); 18 | buffer.putShort((short)2); 19 | buffer.putChar('我'); 20 | 21 | buffer.flip(); 22 | 23 | System.out.println(buffer.getInt()); 24 | System.out.println(buffer.getLong()); 25 | System.out.println(buffer.getDouble()); 26 | System.out.println(buffer.getChar()); 27 | System.out.println(buffer.getShort()); 28 | System.out.println(buffer.getChar()); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/nio/NioTest6.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.nio; 2 | 3 | 4 | import java.nio.ByteBuffer; 5 | 6 | /** 7 | * Slice Buffer与原有buffer共享相同的底层数组 8 | */ 9 | public class NioTest6 { 10 | 11 | public static void main(String[] args) { 12 | ByteBuffer buffer = ByteBuffer.allocate(10); 13 | 14 | for(int i = 0; i < buffer.capacity(); ++i) { 15 | buffer.put((byte)i); 16 | } 17 | 18 | buffer.position(2); 19 | buffer.limit(6); 20 | 21 | ByteBuffer sliceBuffer = buffer.slice(); 22 | 23 | for(int i = 0; i < sliceBuffer.capacity(); ++i) { 24 | byte b = sliceBuffer.get(i); 25 | b *= 2; 26 | sliceBuffer.put(i, b); 27 | } 28 | 29 | buffer.position(0); 30 | buffer.limit(buffer.capacity()); 31 | 32 | while(buffer.hasRemaining()) { 33 | System.out.println(buffer.get()); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/nio/NioTest7.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.nio; 2 | 3 | 4 | import java.nio.ByteBuffer; 5 | 6 | /** 7 | * 只读buffer,我们可以随时将一个普通Buffer调用asReadOnlyBuffer方法返回一个只读Buffer 8 | * 但不能将一个只读Buffer转换为读写Buffer 9 | */ 10 | 11 | public class NioTest7 { 12 | 13 | public static void main(String[] args) { 14 | ByteBuffer buffer = ByteBuffer.allocate(10); 15 | 16 | System.out.println(buffer.getClass()); 17 | 18 | for (int i = 0; i < buffer.capacity(); ++i) { 19 | buffer.put((byte)i); 20 | } 21 | 22 | ByteBuffer readonlyBuffer = buffer.asReadOnlyBuffer(); 23 | 24 | System.out.println(readonlyBuffer.getClass()); 25 | 26 | readonlyBuffer.position(0); 27 | 28 | // readonlyBuffer.put((byte)2); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/nio/NioTest8.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.nio; 2 | 3 | 4 | import java.io.FileInputStream; 5 | import java.io.FileOutputStream; 6 | import java.nio.ByteBuffer; 7 | import java.nio.channels.FileChannel; 8 | 9 | public class NioTest8 { 10 | 11 | public static void main(String[] args) throws Exception { 12 | FileInputStream inputStream = new FileInputStream("input2.txt"); 13 | FileOutputStream outputStream = new FileOutputStream("output2.txt"); 14 | 15 | FileChannel inputChannel = inputStream.getChannel(); 16 | FileChannel outputChannel = outputStream.getChannel(); 17 | 18 | ByteBuffer buffer = ByteBuffer.allocateDirect(512); 19 | 20 | while(true) { 21 | buffer.clear(); 22 | 23 | int read = inputChannel.read(buffer); 24 | 25 | System.out.println("read: " + read); 26 | 27 | if(-1 == read) { 28 | break; 29 | } 30 | 31 | buffer.flip(); 32 | 33 | outputChannel.write(buffer); 34 | } 35 | 36 | inputChannel.close(); 37 | outputChannel.close(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/nio/NioTest9.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.nio; 2 | 3 | 4 | import java.io.RandomAccessFile; 5 | import java.nio.MappedByteBuffer; 6 | import java.nio.channels.FileChannel; 7 | 8 | public class NioTest9 { 9 | 10 | public static void main(String[] args) throws Exception { 11 | RandomAccessFile randomAccessFile = new RandomAccessFile("NioTest9.txt", "rw"); 12 | FileChannel fileChannel = randomAccessFile.getChannel(); 13 | 14 | MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, 5); 15 | 16 | mappedByteBuffer.put(0, (byte)'a'); 17 | mappedByteBuffer.put(3, (byte)'b'); 18 | 19 | randomAccessFile.close(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/proto/MyRequest.java: -------------------------------------------------------------------------------- 1 | // Generated by the protocol buffer compiler. DO NOT EDIT! 2 | // source: Student.proto 3 | 4 | package com.shengsiyuan.proto; 5 | 6 | /** 7 | * Protobuf type {@code com.shengsiyuan.proto.MyRequest} 8 | */ 9 | public final class MyRequest extends 10 | com.google.protobuf.GeneratedMessageV3 implements 11 | // @@protoc_insertion_point(message_implements:com.shengsiyuan.proto.MyRequest) 12 | MyRequestOrBuilder { 13 | // Use MyRequest.newBuilder() to construct. 14 | private MyRequest(com.google.protobuf.GeneratedMessageV3.Builder builder) { 15 | super(builder); 16 | } 17 | private MyRequest() { 18 | username_ = ""; 19 | } 20 | 21 | @java.lang.Override 22 | public final com.google.protobuf.UnknownFieldSet 23 | getUnknownFields() { 24 | return com.google.protobuf.UnknownFieldSet.getDefaultInstance(); 25 | } 26 | private MyRequest( 27 | com.google.protobuf.CodedInputStream input, 28 | com.google.protobuf.ExtensionRegistryLite extensionRegistry) 29 | throws com.google.protobuf.InvalidProtocolBufferException { 30 | this(); 31 | int mutable_bitField0_ = 0; 32 | try { 33 | boolean done = false; 34 | while (!done) { 35 | int tag = input.readTag(); 36 | switch (tag) { 37 | case 0: 38 | done = true; 39 | break; 40 | default: { 41 | if (!input.skipField(tag)) { 42 | done = true; 43 | } 44 | break; 45 | } 46 | case 10: { 47 | java.lang.String s = input.readStringRequireUtf8(); 48 | 49 | username_ = s; 50 | break; 51 | } 52 | } 53 | } 54 | } catch (com.google.protobuf.InvalidProtocolBufferException e) { 55 | throw e.setUnfinishedMessage(this); 56 | } catch (java.io.IOException e) { 57 | throw new com.google.protobuf.InvalidProtocolBufferException( 58 | e).setUnfinishedMessage(this); 59 | } finally { 60 | makeExtensionsImmutable(); 61 | } 62 | } 63 | public static final com.google.protobuf.Descriptors.Descriptor 64 | getDescriptor() { 65 | return com.shengsiyuan.proto.StudentProto.internal_static_com_shengsiyuan_proto_MyRequest_descriptor; 66 | } 67 | 68 | protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable 69 | internalGetFieldAccessorTable() { 70 | return com.shengsiyuan.proto.StudentProto.internal_static_com_shengsiyuan_proto_MyRequest_fieldAccessorTable 71 | .ensureFieldAccessorsInitialized( 72 | com.shengsiyuan.proto.MyRequest.class, com.shengsiyuan.proto.MyRequest.Builder.class); 73 | } 74 | 75 | public static final int USERNAME_FIELD_NUMBER = 1; 76 | private volatile java.lang.Object username_; 77 | /** 78 | * string username = 1; 79 | */ 80 | public java.lang.String getUsername() { 81 | java.lang.Object ref = username_; 82 | if (ref instanceof java.lang.String) { 83 | return (java.lang.String) ref; 84 | } else { 85 | com.google.protobuf.ByteString bs = 86 | (com.google.protobuf.ByteString) ref; 87 | java.lang.String s = bs.toStringUtf8(); 88 | username_ = s; 89 | return s; 90 | } 91 | } 92 | /** 93 | * string username = 1; 94 | */ 95 | public com.google.protobuf.ByteString 96 | getUsernameBytes() { 97 | java.lang.Object ref = username_; 98 | if (ref instanceof java.lang.String) { 99 | com.google.protobuf.ByteString b = 100 | com.google.protobuf.ByteString.copyFromUtf8( 101 | (java.lang.String) ref); 102 | username_ = b; 103 | return b; 104 | } else { 105 | return (com.google.protobuf.ByteString) ref; 106 | } 107 | } 108 | 109 | private byte memoizedIsInitialized = -1; 110 | public final boolean isInitialized() { 111 | byte isInitialized = memoizedIsInitialized; 112 | if (isInitialized == 1) return true; 113 | if (isInitialized == 0) return false; 114 | 115 | memoizedIsInitialized = 1; 116 | return true; 117 | } 118 | 119 | public void writeTo(com.google.protobuf.CodedOutputStream output) 120 | throws java.io.IOException { 121 | if (!getUsernameBytes().isEmpty()) { 122 | com.google.protobuf.GeneratedMessageV3.writeString(output, 1, username_); 123 | } 124 | } 125 | 126 | public int getSerializedSize() { 127 | int size = memoizedSize; 128 | if (size != -1) return size; 129 | 130 | size = 0; 131 | if (!getUsernameBytes().isEmpty()) { 132 | size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, username_); 133 | } 134 | memoizedSize = size; 135 | return size; 136 | } 137 | 138 | private static final long serialVersionUID = 0L; 139 | @java.lang.Override 140 | public boolean equals(final java.lang.Object obj) { 141 | if (obj == this) { 142 | return true; 143 | } 144 | if (!(obj instanceof com.shengsiyuan.proto.MyRequest)) { 145 | return super.equals(obj); 146 | } 147 | com.shengsiyuan.proto.MyRequest other = (com.shengsiyuan.proto.MyRequest) obj; 148 | 149 | boolean result = true; 150 | result = result && getUsername() 151 | .equals(other.getUsername()); 152 | return result; 153 | } 154 | 155 | @java.lang.Override 156 | public int hashCode() { 157 | if (memoizedHashCode != 0) { 158 | return memoizedHashCode; 159 | } 160 | int hash = 41; 161 | hash = (19 * hash) + getDescriptor().hashCode(); 162 | hash = (37 * hash) + USERNAME_FIELD_NUMBER; 163 | hash = (53 * hash) + getUsername().hashCode(); 164 | hash = (29 * hash) + unknownFields.hashCode(); 165 | memoizedHashCode = hash; 166 | return hash; 167 | } 168 | 169 | public static com.shengsiyuan.proto.MyRequest parseFrom( 170 | com.google.protobuf.ByteString data) 171 | throws com.google.protobuf.InvalidProtocolBufferException { 172 | return PARSER.parseFrom(data); 173 | } 174 | public static com.shengsiyuan.proto.MyRequest parseFrom( 175 | com.google.protobuf.ByteString data, 176 | com.google.protobuf.ExtensionRegistryLite extensionRegistry) 177 | throws com.google.protobuf.InvalidProtocolBufferException { 178 | return PARSER.parseFrom(data, extensionRegistry); 179 | } 180 | public static com.shengsiyuan.proto.MyRequest parseFrom(byte[] data) 181 | throws com.google.protobuf.InvalidProtocolBufferException { 182 | return PARSER.parseFrom(data); 183 | } 184 | public static com.shengsiyuan.proto.MyRequest parseFrom( 185 | byte[] data, 186 | com.google.protobuf.ExtensionRegistryLite extensionRegistry) 187 | throws com.google.protobuf.InvalidProtocolBufferException { 188 | return PARSER.parseFrom(data, extensionRegistry); 189 | } 190 | public static com.shengsiyuan.proto.MyRequest parseFrom(java.io.InputStream input) 191 | throws java.io.IOException { 192 | return com.google.protobuf.GeneratedMessageV3 193 | .parseWithIOException(PARSER, input); 194 | } 195 | public static com.shengsiyuan.proto.MyRequest parseFrom( 196 | java.io.InputStream input, 197 | com.google.protobuf.ExtensionRegistryLite extensionRegistry) 198 | throws java.io.IOException { 199 | return com.google.protobuf.GeneratedMessageV3 200 | .parseWithIOException(PARSER, input, extensionRegistry); 201 | } 202 | public static com.shengsiyuan.proto.MyRequest parseDelimitedFrom(java.io.InputStream input) 203 | throws java.io.IOException { 204 | return com.google.protobuf.GeneratedMessageV3 205 | .parseDelimitedWithIOException(PARSER, input); 206 | } 207 | public static com.shengsiyuan.proto.MyRequest parseDelimitedFrom( 208 | java.io.InputStream input, 209 | com.google.protobuf.ExtensionRegistryLite extensionRegistry) 210 | throws java.io.IOException { 211 | return com.google.protobuf.GeneratedMessageV3 212 | .parseDelimitedWithIOException(PARSER, input, extensionRegistry); 213 | } 214 | public static com.shengsiyuan.proto.MyRequest parseFrom( 215 | com.google.protobuf.CodedInputStream input) 216 | throws java.io.IOException { 217 | return com.google.protobuf.GeneratedMessageV3 218 | .parseWithIOException(PARSER, input); 219 | } 220 | public static com.shengsiyuan.proto.MyRequest parseFrom( 221 | com.google.protobuf.CodedInputStream input, 222 | com.google.protobuf.ExtensionRegistryLite extensionRegistry) 223 | throws java.io.IOException { 224 | return com.google.protobuf.GeneratedMessageV3 225 | .parseWithIOException(PARSER, input, extensionRegistry); 226 | } 227 | 228 | public Builder newBuilderForType() { return newBuilder(); } 229 | public static Builder newBuilder() { 230 | return DEFAULT_INSTANCE.toBuilder(); 231 | } 232 | public static Builder newBuilder(com.shengsiyuan.proto.MyRequest prototype) { 233 | return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); 234 | } 235 | public Builder toBuilder() { 236 | return this == DEFAULT_INSTANCE 237 | ? new Builder() : new Builder().mergeFrom(this); 238 | } 239 | 240 | @java.lang.Override 241 | protected Builder newBuilderForType( 242 | com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { 243 | Builder builder = new Builder(parent); 244 | return builder; 245 | } 246 | /** 247 | * Protobuf type {@code com.shengsiyuan.proto.MyRequest} 248 | */ 249 | public static final class Builder extends 250 | com.google.protobuf.GeneratedMessageV3.Builder implements 251 | // @@protoc_insertion_point(builder_implements:com.shengsiyuan.proto.MyRequest) 252 | com.shengsiyuan.proto.MyRequestOrBuilder { 253 | public static final com.google.protobuf.Descriptors.Descriptor 254 | getDescriptor() { 255 | return com.shengsiyuan.proto.StudentProto.internal_static_com_shengsiyuan_proto_MyRequest_descriptor; 256 | } 257 | 258 | protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable 259 | internalGetFieldAccessorTable() { 260 | return com.shengsiyuan.proto.StudentProto.internal_static_com_shengsiyuan_proto_MyRequest_fieldAccessorTable 261 | .ensureFieldAccessorsInitialized( 262 | com.shengsiyuan.proto.MyRequest.class, com.shengsiyuan.proto.MyRequest.Builder.class); 263 | } 264 | 265 | // Construct using com.shengsiyuan.proto.MyRequest.newBuilder() 266 | private Builder() { 267 | maybeForceBuilderInitialization(); 268 | } 269 | 270 | private Builder( 271 | com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { 272 | super(parent); 273 | maybeForceBuilderInitialization(); 274 | } 275 | private void maybeForceBuilderInitialization() { 276 | if (com.google.protobuf.GeneratedMessageV3 277 | .alwaysUseFieldBuilders) { 278 | } 279 | } 280 | public Builder clear() { 281 | super.clear(); 282 | username_ = ""; 283 | 284 | return this; 285 | } 286 | 287 | public com.google.protobuf.Descriptors.Descriptor 288 | getDescriptorForType() { 289 | return com.shengsiyuan.proto.StudentProto.internal_static_com_shengsiyuan_proto_MyRequest_descriptor; 290 | } 291 | 292 | public com.shengsiyuan.proto.MyRequest getDefaultInstanceForType() { 293 | return com.shengsiyuan.proto.MyRequest.getDefaultInstance(); 294 | } 295 | 296 | public com.shengsiyuan.proto.MyRequest build() { 297 | com.shengsiyuan.proto.MyRequest result = buildPartial(); 298 | if (!result.isInitialized()) { 299 | throw newUninitializedMessageException(result); 300 | } 301 | return result; 302 | } 303 | 304 | public com.shengsiyuan.proto.MyRequest buildPartial() { 305 | com.shengsiyuan.proto.MyRequest result = new com.shengsiyuan.proto.MyRequest(this); 306 | result.username_ = username_; 307 | onBuilt(); 308 | return result; 309 | } 310 | 311 | public Builder clone() { 312 | return (Builder) super.clone(); 313 | } 314 | public Builder setField( 315 | com.google.protobuf.Descriptors.FieldDescriptor field, 316 | Object value) { 317 | return (Builder) super.setField(field, value); 318 | } 319 | public Builder clearField( 320 | com.google.protobuf.Descriptors.FieldDescriptor field) { 321 | return (Builder) super.clearField(field); 322 | } 323 | public Builder clearOneof( 324 | com.google.protobuf.Descriptors.OneofDescriptor oneof) { 325 | return (Builder) super.clearOneof(oneof); 326 | } 327 | public Builder setRepeatedField( 328 | com.google.protobuf.Descriptors.FieldDescriptor field, 329 | int index, Object value) { 330 | return (Builder) super.setRepeatedField(field, index, value); 331 | } 332 | public Builder addRepeatedField( 333 | com.google.protobuf.Descriptors.FieldDescriptor field, 334 | Object value) { 335 | return (Builder) super.addRepeatedField(field, value); 336 | } 337 | public Builder mergeFrom(com.google.protobuf.Message other) { 338 | if (other instanceof com.shengsiyuan.proto.MyRequest) { 339 | return mergeFrom((com.shengsiyuan.proto.MyRequest)other); 340 | } else { 341 | super.mergeFrom(other); 342 | return this; 343 | } 344 | } 345 | 346 | public Builder mergeFrom(com.shengsiyuan.proto.MyRequest other) { 347 | if (other == com.shengsiyuan.proto.MyRequest.getDefaultInstance()) return this; 348 | if (!other.getUsername().isEmpty()) { 349 | username_ = other.username_; 350 | onChanged(); 351 | } 352 | onChanged(); 353 | return this; 354 | } 355 | 356 | public final boolean isInitialized() { 357 | return true; 358 | } 359 | 360 | public Builder mergeFrom( 361 | com.google.protobuf.CodedInputStream input, 362 | com.google.protobuf.ExtensionRegistryLite extensionRegistry) 363 | throws java.io.IOException { 364 | com.shengsiyuan.proto.MyRequest parsedMessage = null; 365 | try { 366 | parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); 367 | } catch (com.google.protobuf.InvalidProtocolBufferException e) { 368 | parsedMessage = (com.shengsiyuan.proto.MyRequest) e.getUnfinishedMessage(); 369 | throw e.unwrapIOException(); 370 | } finally { 371 | if (parsedMessage != null) { 372 | mergeFrom(parsedMessage); 373 | } 374 | } 375 | return this; 376 | } 377 | 378 | private java.lang.Object username_ = ""; 379 | /** 380 | * string username = 1; 381 | */ 382 | public java.lang.String getUsername() { 383 | java.lang.Object ref = username_; 384 | if (!(ref instanceof java.lang.String)) { 385 | com.google.protobuf.ByteString bs = 386 | (com.google.protobuf.ByteString) ref; 387 | java.lang.String s = bs.toStringUtf8(); 388 | username_ = s; 389 | return s; 390 | } else { 391 | return (java.lang.String) ref; 392 | } 393 | } 394 | /** 395 | * string username = 1; 396 | */ 397 | public com.google.protobuf.ByteString 398 | getUsernameBytes() { 399 | java.lang.Object ref = username_; 400 | if (ref instanceof String) { 401 | com.google.protobuf.ByteString b = 402 | com.google.protobuf.ByteString.copyFromUtf8( 403 | (java.lang.String) ref); 404 | username_ = b; 405 | return b; 406 | } else { 407 | return (com.google.protobuf.ByteString) ref; 408 | } 409 | } 410 | /** 411 | * string username = 1; 412 | */ 413 | public Builder setUsername( 414 | java.lang.String value) { 415 | if (value == null) { 416 | throw new NullPointerException(); 417 | } 418 | 419 | username_ = value; 420 | onChanged(); 421 | return this; 422 | } 423 | /** 424 | * string username = 1; 425 | */ 426 | public Builder clearUsername() { 427 | 428 | username_ = getDefaultInstance().getUsername(); 429 | onChanged(); 430 | return this; 431 | } 432 | /** 433 | * string username = 1; 434 | */ 435 | public Builder setUsernameBytes( 436 | com.google.protobuf.ByteString value) { 437 | if (value == null) { 438 | throw new NullPointerException(); 439 | } 440 | checkByteStringIsUtf8(value); 441 | 442 | username_ = value; 443 | onChanged(); 444 | return this; 445 | } 446 | public final Builder setUnknownFields( 447 | final com.google.protobuf.UnknownFieldSet unknownFields) { 448 | return this; 449 | } 450 | 451 | public final Builder mergeUnknownFields( 452 | final com.google.protobuf.UnknownFieldSet unknownFields) { 453 | return this; 454 | } 455 | 456 | 457 | // @@protoc_insertion_point(builder_scope:com.shengsiyuan.proto.MyRequest) 458 | } 459 | 460 | // @@protoc_insertion_point(class_scope:com.shengsiyuan.proto.MyRequest) 461 | private static final com.shengsiyuan.proto.MyRequest DEFAULT_INSTANCE; 462 | static { 463 | DEFAULT_INSTANCE = new com.shengsiyuan.proto.MyRequest(); 464 | } 465 | 466 | public static com.shengsiyuan.proto.MyRequest getDefaultInstance() { 467 | return DEFAULT_INSTANCE; 468 | } 469 | 470 | private static final com.google.protobuf.Parser 471 | PARSER = new com.google.protobuf.AbstractParser() { 472 | public MyRequest parsePartialFrom( 473 | com.google.protobuf.CodedInputStream input, 474 | com.google.protobuf.ExtensionRegistryLite extensionRegistry) 475 | throws com.google.protobuf.InvalidProtocolBufferException { 476 | return new MyRequest(input, extensionRegistry); 477 | } 478 | }; 479 | 480 | public static com.google.protobuf.Parser parser() { 481 | return PARSER; 482 | } 483 | 484 | @java.lang.Override 485 | public com.google.protobuf.Parser getParserForType() { 486 | return PARSER; 487 | } 488 | 489 | public com.shengsiyuan.proto.MyRequest getDefaultInstanceForType() { 490 | return DEFAULT_INSTANCE; 491 | } 492 | 493 | } 494 | 495 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/proto/MyRequestOrBuilder.java: -------------------------------------------------------------------------------- 1 | // Generated by the protocol buffer compiler. DO NOT EDIT! 2 | // source: Student.proto 3 | 4 | package com.shengsiyuan.proto; 5 | 6 | public interface MyRequestOrBuilder extends 7 | // @@protoc_insertion_point(interface_extends:com.shengsiyuan.proto.MyRequest) 8 | com.google.protobuf.MessageOrBuilder { 9 | 10 | /** 11 | * string username = 1; 12 | */ 13 | java.lang.String getUsername(); 14 | /** 15 | * string username = 1; 16 | */ 17 | com.google.protobuf.ByteString 18 | getUsernameBytes(); 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/proto/MyResponseOrBuilder.java: -------------------------------------------------------------------------------- 1 | // Generated by the protocol buffer compiler. DO NOT EDIT! 2 | // source: Student.proto 3 | 4 | package com.shengsiyuan.proto; 5 | 6 | public interface MyResponseOrBuilder extends 7 | // @@protoc_insertion_point(interface_extends:com.shengsiyuan.proto.MyResponse) 8 | com.google.protobuf.MessageOrBuilder { 9 | 10 | /** 11 | * string realname = 2; 12 | */ 13 | java.lang.String getRealname(); 14 | /** 15 | * string realname = 2; 16 | */ 17 | com.google.protobuf.ByteString 18 | getRealnameBytes(); 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/proto/StreamRequestOrBuilder.java: -------------------------------------------------------------------------------- 1 | // Generated by the protocol buffer compiler. DO NOT EDIT! 2 | // source: Student.proto 3 | 4 | package com.shengsiyuan.proto; 5 | 6 | public interface StreamRequestOrBuilder extends 7 | // @@protoc_insertion_point(interface_extends:com.shengsiyuan.proto.StreamRequest) 8 | com.google.protobuf.MessageOrBuilder { 9 | 10 | /** 11 | * string request_info = 1; 12 | */ 13 | java.lang.String getRequestInfo(); 14 | /** 15 | * string request_info = 1; 16 | */ 17 | com.google.protobuf.ByteString 18 | getRequestInfoBytes(); 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/proto/StreamResponseOrBuilder.java: -------------------------------------------------------------------------------- 1 | // Generated by the protocol buffer compiler. DO NOT EDIT! 2 | // source: Student.proto 3 | 4 | package com.shengsiyuan.proto; 5 | 6 | public interface StreamResponseOrBuilder extends 7 | // @@protoc_insertion_point(interface_extends:com.shengsiyuan.proto.StreamResponse) 8 | com.google.protobuf.MessageOrBuilder { 9 | 10 | /** 11 | * string response_info = 1; 12 | */ 13 | java.lang.String getResponseInfo(); 14 | /** 15 | * string response_info = 1; 16 | */ 17 | com.google.protobuf.ByteString 18 | getResponseInfoBytes(); 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/proto/StudentProto.java: -------------------------------------------------------------------------------- 1 | // Generated by the protocol buffer compiler. DO NOT EDIT! 2 | // source: Student.proto 3 | 4 | package com.shengsiyuan.proto; 5 | 6 | public final class StudentProto { 7 | private StudentProto() {} 8 | public static void registerAllExtensions( 9 | com.google.protobuf.ExtensionRegistryLite registry) { 10 | } 11 | 12 | public static void registerAllExtensions( 13 | com.google.protobuf.ExtensionRegistry registry) { 14 | registerAllExtensions( 15 | (com.google.protobuf.ExtensionRegistryLite) registry); 16 | } 17 | static final com.google.protobuf.Descriptors.Descriptor 18 | internal_static_com_shengsiyuan_proto_MyRequest_descriptor; 19 | static final 20 | com.google.protobuf.GeneratedMessageV3.FieldAccessorTable 21 | internal_static_com_shengsiyuan_proto_MyRequest_fieldAccessorTable; 22 | static final com.google.protobuf.Descriptors.Descriptor 23 | internal_static_com_shengsiyuan_proto_MyResponse_descriptor; 24 | static final 25 | com.google.protobuf.GeneratedMessageV3.FieldAccessorTable 26 | internal_static_com_shengsiyuan_proto_MyResponse_fieldAccessorTable; 27 | static final com.google.protobuf.Descriptors.Descriptor 28 | internal_static_com_shengsiyuan_proto_StudentRequest_descriptor; 29 | static final 30 | com.google.protobuf.GeneratedMessageV3.FieldAccessorTable 31 | internal_static_com_shengsiyuan_proto_StudentRequest_fieldAccessorTable; 32 | static final com.google.protobuf.Descriptors.Descriptor 33 | internal_static_com_shengsiyuan_proto_StudentResponse_descriptor; 34 | static final 35 | com.google.protobuf.GeneratedMessageV3.FieldAccessorTable 36 | internal_static_com_shengsiyuan_proto_StudentResponse_fieldAccessorTable; 37 | static final com.google.protobuf.Descriptors.Descriptor 38 | internal_static_com_shengsiyuan_proto_StudentResponseList_descriptor; 39 | static final 40 | com.google.protobuf.GeneratedMessageV3.FieldAccessorTable 41 | internal_static_com_shengsiyuan_proto_StudentResponseList_fieldAccessorTable; 42 | static final com.google.protobuf.Descriptors.Descriptor 43 | internal_static_com_shengsiyuan_proto_StreamRequest_descriptor; 44 | static final 45 | com.google.protobuf.GeneratedMessageV3.FieldAccessorTable 46 | internal_static_com_shengsiyuan_proto_StreamRequest_fieldAccessorTable; 47 | static final com.google.protobuf.Descriptors.Descriptor 48 | internal_static_com_shengsiyuan_proto_StreamResponse_descriptor; 49 | static final 50 | com.google.protobuf.GeneratedMessageV3.FieldAccessorTable 51 | internal_static_com_shengsiyuan_proto_StreamResponse_fieldAccessorTable; 52 | 53 | public static com.google.protobuf.Descriptors.FileDescriptor 54 | getDescriptor() { 55 | return descriptor; 56 | } 57 | private static com.google.protobuf.Descriptors.FileDescriptor 58 | descriptor; 59 | static { 60 | java.lang.String[] descriptorData = { 61 | "\n\rStudent.proto\022\025com.shengsiyuan.proto\"\035" + 62 | "\n\tMyRequest\022\020\n\010username\030\001 \001(\t\"\036\n\nMyRespo" + 63 | "nse\022\020\n\010realname\030\002 \001(\t\"\035\n\016StudentRequest\022" + 64 | "\013\n\003age\030\001 \001(\005\":\n\017StudentResponse\022\014\n\004name\030" + 65 | "\001 \001(\t\022\013\n\003age\030\002 \001(\005\022\014\n\004city\030\003 \001(\t\"V\n\023Stud" + 66 | "entResponseList\022?\n\017studentResponse\030\001 \003(\013" + 67 | "2&.com.shengsiyuan.proto.StudentResponse" + 68 | "\"%\n\rStreamRequest\022\024\n\014request_info\030\001 \001(\t\"" + 69 | "\'\n\016StreamResponse\022\025\n\rresponse_info\030\001 \001(\t" + 70 | "2\247\003\n\016StudentService\022^\n\025GetRealNameByUser", 71 | "name\022 .com.shengsiyuan.proto.MyRequest\032!" + 72 | ".com.shengsiyuan.proto.MyResponse\"\000\022e\n\020G" + 73 | "etStudentsByAge\022%.com.shengsiyuan.proto." + 74 | "StudentRequest\032&.com.shengsiyuan.proto.S" + 75 | "tudentResponse\"\0000\001\022q\n\030GetStudentsWrapper" + 76 | "ByAges\022%.com.shengsiyuan.proto.StudentRe" + 77 | "quest\032*.com.shengsiyuan.proto.StudentRes" + 78 | "ponseList\"\000(\001\022[\n\006BiTalk\022$.com.shengsiyua" + 79 | "n.proto.StreamRequest\032%.com.shengsiyuan." + 80 | "proto.StreamResponse\"\000(\0010\001B\'\n\025com.shengs", 81 | "iyuan.protoB\014StudentProtoP\001b\006proto3" 82 | }; 83 | com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = 84 | new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { 85 | public com.google.protobuf.ExtensionRegistry assignDescriptors( 86 | com.google.protobuf.Descriptors.FileDescriptor root) { 87 | descriptor = root; 88 | return null; 89 | } 90 | }; 91 | com.google.protobuf.Descriptors.FileDescriptor 92 | .internalBuildGeneratedFileFrom(descriptorData, 93 | new com.google.protobuf.Descriptors.FileDescriptor[] { 94 | }, assigner); 95 | internal_static_com_shengsiyuan_proto_MyRequest_descriptor = 96 | getDescriptor().getMessageTypes().get(0); 97 | internal_static_com_shengsiyuan_proto_MyRequest_fieldAccessorTable = new 98 | com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( 99 | internal_static_com_shengsiyuan_proto_MyRequest_descriptor, 100 | new java.lang.String[] { "Username", }); 101 | internal_static_com_shengsiyuan_proto_MyResponse_descriptor = 102 | getDescriptor().getMessageTypes().get(1); 103 | internal_static_com_shengsiyuan_proto_MyResponse_fieldAccessorTable = new 104 | com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( 105 | internal_static_com_shengsiyuan_proto_MyResponse_descriptor, 106 | new java.lang.String[] { "Realname", }); 107 | internal_static_com_shengsiyuan_proto_StudentRequest_descriptor = 108 | getDescriptor().getMessageTypes().get(2); 109 | internal_static_com_shengsiyuan_proto_StudentRequest_fieldAccessorTable = new 110 | com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( 111 | internal_static_com_shengsiyuan_proto_StudentRequest_descriptor, 112 | new java.lang.String[] { "Age", }); 113 | internal_static_com_shengsiyuan_proto_StudentResponse_descriptor = 114 | getDescriptor().getMessageTypes().get(3); 115 | internal_static_com_shengsiyuan_proto_StudentResponse_fieldAccessorTable = new 116 | com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( 117 | internal_static_com_shengsiyuan_proto_StudentResponse_descriptor, 118 | new java.lang.String[] { "Name", "Age", "City", }); 119 | internal_static_com_shengsiyuan_proto_StudentResponseList_descriptor = 120 | getDescriptor().getMessageTypes().get(4); 121 | internal_static_com_shengsiyuan_proto_StudentResponseList_fieldAccessorTable = new 122 | com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( 123 | internal_static_com_shengsiyuan_proto_StudentResponseList_descriptor, 124 | new java.lang.String[] { "StudentResponse", }); 125 | internal_static_com_shengsiyuan_proto_StreamRequest_descriptor = 126 | getDescriptor().getMessageTypes().get(5); 127 | internal_static_com_shengsiyuan_proto_StreamRequest_fieldAccessorTable = new 128 | com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( 129 | internal_static_com_shengsiyuan_proto_StreamRequest_descriptor, 130 | new java.lang.String[] { "RequestInfo", }); 131 | internal_static_com_shengsiyuan_proto_StreamResponse_descriptor = 132 | getDescriptor().getMessageTypes().get(6); 133 | internal_static_com_shengsiyuan_proto_StreamResponse_fieldAccessorTable = new 134 | com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( 135 | internal_static_com_shengsiyuan_proto_StreamResponse_descriptor, 136 | new java.lang.String[] { "ResponseInfo", }); 137 | } 138 | 139 | // @@protoc_insertion_point(outer_class_scope) 140 | } 141 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/proto/StudentRequest.java: -------------------------------------------------------------------------------- 1 | // Generated by the protocol buffer compiler. DO NOT EDIT! 2 | // source: Student.proto 3 | 4 | package com.shengsiyuan.proto; 5 | 6 | /** 7 | * Protobuf type {@code com.shengsiyuan.proto.StudentRequest} 8 | */ 9 | public final class StudentRequest extends 10 | com.google.protobuf.GeneratedMessageV3 implements 11 | // @@protoc_insertion_point(message_implements:com.shengsiyuan.proto.StudentRequest) 12 | StudentRequestOrBuilder { 13 | // Use StudentRequest.newBuilder() to construct. 14 | private StudentRequest(com.google.protobuf.GeneratedMessageV3.Builder builder) { 15 | super(builder); 16 | } 17 | private StudentRequest() { 18 | age_ = 0; 19 | } 20 | 21 | @java.lang.Override 22 | public final com.google.protobuf.UnknownFieldSet 23 | getUnknownFields() { 24 | return com.google.protobuf.UnknownFieldSet.getDefaultInstance(); 25 | } 26 | private StudentRequest( 27 | com.google.protobuf.CodedInputStream input, 28 | com.google.protobuf.ExtensionRegistryLite extensionRegistry) 29 | throws com.google.protobuf.InvalidProtocolBufferException { 30 | this(); 31 | int mutable_bitField0_ = 0; 32 | try { 33 | boolean done = false; 34 | while (!done) { 35 | int tag = input.readTag(); 36 | switch (tag) { 37 | case 0: 38 | done = true; 39 | break; 40 | default: { 41 | if (!input.skipField(tag)) { 42 | done = true; 43 | } 44 | break; 45 | } 46 | case 8: { 47 | 48 | age_ = input.readInt32(); 49 | break; 50 | } 51 | } 52 | } 53 | } catch (com.google.protobuf.InvalidProtocolBufferException e) { 54 | throw e.setUnfinishedMessage(this); 55 | } catch (java.io.IOException e) { 56 | throw new com.google.protobuf.InvalidProtocolBufferException( 57 | e).setUnfinishedMessage(this); 58 | } finally { 59 | makeExtensionsImmutable(); 60 | } 61 | } 62 | public static final com.google.protobuf.Descriptors.Descriptor 63 | getDescriptor() { 64 | return com.shengsiyuan.proto.StudentProto.internal_static_com_shengsiyuan_proto_StudentRequest_descriptor; 65 | } 66 | 67 | protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable 68 | internalGetFieldAccessorTable() { 69 | return com.shengsiyuan.proto.StudentProto.internal_static_com_shengsiyuan_proto_StudentRequest_fieldAccessorTable 70 | .ensureFieldAccessorsInitialized( 71 | com.shengsiyuan.proto.StudentRequest.class, com.shengsiyuan.proto.StudentRequest.Builder.class); 72 | } 73 | 74 | public static final int AGE_FIELD_NUMBER = 1; 75 | private int age_; 76 | /** 77 | * int32 age = 1; 78 | */ 79 | public int getAge() { 80 | return age_; 81 | } 82 | 83 | private byte memoizedIsInitialized = -1; 84 | public final boolean isInitialized() { 85 | byte isInitialized = memoizedIsInitialized; 86 | if (isInitialized == 1) return true; 87 | if (isInitialized == 0) return false; 88 | 89 | memoizedIsInitialized = 1; 90 | return true; 91 | } 92 | 93 | public void writeTo(com.google.protobuf.CodedOutputStream output) 94 | throws java.io.IOException { 95 | if (age_ != 0) { 96 | output.writeInt32(1, age_); 97 | } 98 | } 99 | 100 | public int getSerializedSize() { 101 | int size = memoizedSize; 102 | if (size != -1) return size; 103 | 104 | size = 0; 105 | if (age_ != 0) { 106 | size += com.google.protobuf.CodedOutputStream 107 | .computeInt32Size(1, age_); 108 | } 109 | memoizedSize = size; 110 | return size; 111 | } 112 | 113 | private static final long serialVersionUID = 0L; 114 | @java.lang.Override 115 | public boolean equals(final java.lang.Object obj) { 116 | if (obj == this) { 117 | return true; 118 | } 119 | if (!(obj instanceof com.shengsiyuan.proto.StudentRequest)) { 120 | return super.equals(obj); 121 | } 122 | com.shengsiyuan.proto.StudentRequest other = (com.shengsiyuan.proto.StudentRequest) obj; 123 | 124 | boolean result = true; 125 | result = result && (getAge() 126 | == other.getAge()); 127 | return result; 128 | } 129 | 130 | @java.lang.Override 131 | public int hashCode() { 132 | if (memoizedHashCode != 0) { 133 | return memoizedHashCode; 134 | } 135 | int hash = 41; 136 | hash = (19 * hash) + getDescriptor().hashCode(); 137 | hash = (37 * hash) + AGE_FIELD_NUMBER; 138 | hash = (53 * hash) + getAge(); 139 | hash = (29 * hash) + unknownFields.hashCode(); 140 | memoizedHashCode = hash; 141 | return hash; 142 | } 143 | 144 | public static com.shengsiyuan.proto.StudentRequest parseFrom( 145 | com.google.protobuf.ByteString data) 146 | throws com.google.protobuf.InvalidProtocolBufferException { 147 | return PARSER.parseFrom(data); 148 | } 149 | public static com.shengsiyuan.proto.StudentRequest parseFrom( 150 | com.google.protobuf.ByteString data, 151 | com.google.protobuf.ExtensionRegistryLite extensionRegistry) 152 | throws com.google.protobuf.InvalidProtocolBufferException { 153 | return PARSER.parseFrom(data, extensionRegistry); 154 | } 155 | public static com.shengsiyuan.proto.StudentRequest parseFrom(byte[] data) 156 | throws com.google.protobuf.InvalidProtocolBufferException { 157 | return PARSER.parseFrom(data); 158 | } 159 | public static com.shengsiyuan.proto.StudentRequest parseFrom( 160 | byte[] data, 161 | com.google.protobuf.ExtensionRegistryLite extensionRegistry) 162 | throws com.google.protobuf.InvalidProtocolBufferException { 163 | return PARSER.parseFrom(data, extensionRegistry); 164 | } 165 | public static com.shengsiyuan.proto.StudentRequest parseFrom(java.io.InputStream input) 166 | throws java.io.IOException { 167 | return com.google.protobuf.GeneratedMessageV3 168 | .parseWithIOException(PARSER, input); 169 | } 170 | public static com.shengsiyuan.proto.StudentRequest parseFrom( 171 | java.io.InputStream input, 172 | com.google.protobuf.ExtensionRegistryLite extensionRegistry) 173 | throws java.io.IOException { 174 | return com.google.protobuf.GeneratedMessageV3 175 | .parseWithIOException(PARSER, input, extensionRegistry); 176 | } 177 | public static com.shengsiyuan.proto.StudentRequest parseDelimitedFrom(java.io.InputStream input) 178 | throws java.io.IOException { 179 | return com.google.protobuf.GeneratedMessageV3 180 | .parseDelimitedWithIOException(PARSER, input); 181 | } 182 | public static com.shengsiyuan.proto.StudentRequest parseDelimitedFrom( 183 | java.io.InputStream input, 184 | com.google.protobuf.ExtensionRegistryLite extensionRegistry) 185 | throws java.io.IOException { 186 | return com.google.protobuf.GeneratedMessageV3 187 | .parseDelimitedWithIOException(PARSER, input, extensionRegistry); 188 | } 189 | public static com.shengsiyuan.proto.StudentRequest parseFrom( 190 | com.google.protobuf.CodedInputStream input) 191 | throws java.io.IOException { 192 | return com.google.protobuf.GeneratedMessageV3 193 | .parseWithIOException(PARSER, input); 194 | } 195 | public static com.shengsiyuan.proto.StudentRequest parseFrom( 196 | com.google.protobuf.CodedInputStream input, 197 | com.google.protobuf.ExtensionRegistryLite extensionRegistry) 198 | throws java.io.IOException { 199 | return com.google.protobuf.GeneratedMessageV3 200 | .parseWithIOException(PARSER, input, extensionRegistry); 201 | } 202 | 203 | public Builder newBuilderForType() { return newBuilder(); } 204 | public static Builder newBuilder() { 205 | return DEFAULT_INSTANCE.toBuilder(); 206 | } 207 | public static Builder newBuilder(com.shengsiyuan.proto.StudentRequest prototype) { 208 | return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); 209 | } 210 | public Builder toBuilder() { 211 | return this == DEFAULT_INSTANCE 212 | ? new Builder() : new Builder().mergeFrom(this); 213 | } 214 | 215 | @java.lang.Override 216 | protected Builder newBuilderForType( 217 | com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { 218 | Builder builder = new Builder(parent); 219 | return builder; 220 | } 221 | /** 222 | * Protobuf type {@code com.shengsiyuan.proto.StudentRequest} 223 | */ 224 | public static final class Builder extends 225 | com.google.protobuf.GeneratedMessageV3.Builder implements 226 | // @@protoc_insertion_point(builder_implements:com.shengsiyuan.proto.StudentRequest) 227 | com.shengsiyuan.proto.StudentRequestOrBuilder { 228 | public static final com.google.protobuf.Descriptors.Descriptor 229 | getDescriptor() { 230 | return com.shengsiyuan.proto.StudentProto.internal_static_com_shengsiyuan_proto_StudentRequest_descriptor; 231 | } 232 | 233 | protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable 234 | internalGetFieldAccessorTable() { 235 | return com.shengsiyuan.proto.StudentProto.internal_static_com_shengsiyuan_proto_StudentRequest_fieldAccessorTable 236 | .ensureFieldAccessorsInitialized( 237 | com.shengsiyuan.proto.StudentRequest.class, com.shengsiyuan.proto.StudentRequest.Builder.class); 238 | } 239 | 240 | // Construct using com.shengsiyuan.proto.StudentRequest.newBuilder() 241 | private Builder() { 242 | maybeForceBuilderInitialization(); 243 | } 244 | 245 | private Builder( 246 | com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { 247 | super(parent); 248 | maybeForceBuilderInitialization(); 249 | } 250 | private void maybeForceBuilderInitialization() { 251 | if (com.google.protobuf.GeneratedMessageV3 252 | .alwaysUseFieldBuilders) { 253 | } 254 | } 255 | public Builder clear() { 256 | super.clear(); 257 | age_ = 0; 258 | 259 | return this; 260 | } 261 | 262 | public com.google.protobuf.Descriptors.Descriptor 263 | getDescriptorForType() { 264 | return com.shengsiyuan.proto.StudentProto.internal_static_com_shengsiyuan_proto_StudentRequest_descriptor; 265 | } 266 | 267 | public com.shengsiyuan.proto.StudentRequest getDefaultInstanceForType() { 268 | return com.shengsiyuan.proto.StudentRequest.getDefaultInstance(); 269 | } 270 | 271 | public com.shengsiyuan.proto.StudentRequest build() { 272 | com.shengsiyuan.proto.StudentRequest result = buildPartial(); 273 | if (!result.isInitialized()) { 274 | throw newUninitializedMessageException(result); 275 | } 276 | return result; 277 | } 278 | 279 | public com.shengsiyuan.proto.StudentRequest buildPartial() { 280 | com.shengsiyuan.proto.StudentRequest result = new com.shengsiyuan.proto.StudentRequest(this); 281 | result.age_ = age_; 282 | onBuilt(); 283 | return result; 284 | } 285 | 286 | public Builder clone() { 287 | return (Builder) super.clone(); 288 | } 289 | public Builder setField( 290 | com.google.protobuf.Descriptors.FieldDescriptor field, 291 | Object value) { 292 | return (Builder) super.setField(field, value); 293 | } 294 | public Builder clearField( 295 | com.google.protobuf.Descriptors.FieldDescriptor field) { 296 | return (Builder) super.clearField(field); 297 | } 298 | public Builder clearOneof( 299 | com.google.protobuf.Descriptors.OneofDescriptor oneof) { 300 | return (Builder) super.clearOneof(oneof); 301 | } 302 | public Builder setRepeatedField( 303 | com.google.protobuf.Descriptors.FieldDescriptor field, 304 | int index, Object value) { 305 | return (Builder) super.setRepeatedField(field, index, value); 306 | } 307 | public Builder addRepeatedField( 308 | com.google.protobuf.Descriptors.FieldDescriptor field, 309 | Object value) { 310 | return (Builder) super.addRepeatedField(field, value); 311 | } 312 | public Builder mergeFrom(com.google.protobuf.Message other) { 313 | if (other instanceof com.shengsiyuan.proto.StudentRequest) { 314 | return mergeFrom((com.shengsiyuan.proto.StudentRequest)other); 315 | } else { 316 | super.mergeFrom(other); 317 | return this; 318 | } 319 | } 320 | 321 | public Builder mergeFrom(com.shengsiyuan.proto.StudentRequest other) { 322 | if (other == com.shengsiyuan.proto.StudentRequest.getDefaultInstance()) return this; 323 | if (other.getAge() != 0) { 324 | setAge(other.getAge()); 325 | } 326 | onChanged(); 327 | return this; 328 | } 329 | 330 | public final boolean isInitialized() { 331 | return true; 332 | } 333 | 334 | public Builder mergeFrom( 335 | com.google.protobuf.CodedInputStream input, 336 | com.google.protobuf.ExtensionRegistryLite extensionRegistry) 337 | throws java.io.IOException { 338 | com.shengsiyuan.proto.StudentRequest parsedMessage = null; 339 | try { 340 | parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); 341 | } catch (com.google.protobuf.InvalidProtocolBufferException e) { 342 | parsedMessage = (com.shengsiyuan.proto.StudentRequest) e.getUnfinishedMessage(); 343 | throw e.unwrapIOException(); 344 | } finally { 345 | if (parsedMessage != null) { 346 | mergeFrom(parsedMessage); 347 | } 348 | } 349 | return this; 350 | } 351 | 352 | private int age_ ; 353 | /** 354 | * int32 age = 1; 355 | */ 356 | public int getAge() { 357 | return age_; 358 | } 359 | /** 360 | * int32 age = 1; 361 | */ 362 | public Builder setAge(int value) { 363 | 364 | age_ = value; 365 | onChanged(); 366 | return this; 367 | } 368 | /** 369 | * int32 age = 1; 370 | */ 371 | public Builder clearAge() { 372 | 373 | age_ = 0; 374 | onChanged(); 375 | return this; 376 | } 377 | public final Builder setUnknownFields( 378 | final com.google.protobuf.UnknownFieldSet unknownFields) { 379 | return this; 380 | } 381 | 382 | public final Builder mergeUnknownFields( 383 | final com.google.protobuf.UnknownFieldSet unknownFields) { 384 | return this; 385 | } 386 | 387 | 388 | // @@protoc_insertion_point(builder_scope:com.shengsiyuan.proto.StudentRequest) 389 | } 390 | 391 | // @@protoc_insertion_point(class_scope:com.shengsiyuan.proto.StudentRequest) 392 | private static final com.shengsiyuan.proto.StudentRequest DEFAULT_INSTANCE; 393 | static { 394 | DEFAULT_INSTANCE = new com.shengsiyuan.proto.StudentRequest(); 395 | } 396 | 397 | public static com.shengsiyuan.proto.StudentRequest getDefaultInstance() { 398 | return DEFAULT_INSTANCE; 399 | } 400 | 401 | private static final com.google.protobuf.Parser 402 | PARSER = new com.google.protobuf.AbstractParser() { 403 | public StudentRequest parsePartialFrom( 404 | com.google.protobuf.CodedInputStream input, 405 | com.google.protobuf.ExtensionRegistryLite extensionRegistry) 406 | throws com.google.protobuf.InvalidProtocolBufferException { 407 | return new StudentRequest(input, extensionRegistry); 408 | } 409 | }; 410 | 411 | public static com.google.protobuf.Parser parser() { 412 | return PARSER; 413 | } 414 | 415 | @java.lang.Override 416 | public com.google.protobuf.Parser getParserForType() { 417 | return PARSER; 418 | } 419 | 420 | public com.shengsiyuan.proto.StudentRequest getDefaultInstanceForType() { 421 | return DEFAULT_INSTANCE; 422 | } 423 | 424 | } 425 | 426 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/proto/StudentRequestOrBuilder.java: -------------------------------------------------------------------------------- 1 | // Generated by the protocol buffer compiler. DO NOT EDIT! 2 | // source: Student.proto 3 | 4 | package com.shengsiyuan.proto; 5 | 6 | public interface StudentRequestOrBuilder extends 7 | // @@protoc_insertion_point(interface_extends:com.shengsiyuan.proto.StudentRequest) 8 | com.google.protobuf.MessageOrBuilder { 9 | 10 | /** 11 | * int32 age = 1; 12 | */ 13 | int getAge(); 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/proto/StudentResponseListOrBuilder.java: -------------------------------------------------------------------------------- 1 | // Generated by the protocol buffer compiler. DO NOT EDIT! 2 | // source: Student.proto 3 | 4 | package com.shengsiyuan.proto; 5 | 6 | public interface StudentResponseListOrBuilder extends 7 | // @@protoc_insertion_point(interface_extends:com.shengsiyuan.proto.StudentResponseList) 8 | com.google.protobuf.MessageOrBuilder { 9 | 10 | /** 11 | * repeated .com.shengsiyuan.proto.StudentResponse studentResponse = 1; 12 | */ 13 | java.util.List 14 | getStudentResponseList(); 15 | /** 16 | * repeated .com.shengsiyuan.proto.StudentResponse studentResponse = 1; 17 | */ 18 | com.shengsiyuan.proto.StudentResponse getStudentResponse(int index); 19 | /** 20 | * repeated .com.shengsiyuan.proto.StudentResponse studentResponse = 1; 21 | */ 22 | int getStudentResponseCount(); 23 | /** 24 | * repeated .com.shengsiyuan.proto.StudentResponse studentResponse = 1; 25 | */ 26 | java.util.List 27 | getStudentResponseOrBuilderList(); 28 | /** 29 | * repeated .com.shengsiyuan.proto.StudentResponse studentResponse = 1; 30 | */ 31 | com.shengsiyuan.proto.StudentResponseOrBuilder getStudentResponseOrBuilder( 32 | int index); 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/proto/StudentResponseOrBuilder.java: -------------------------------------------------------------------------------- 1 | // Generated by the protocol buffer compiler. DO NOT EDIT! 2 | // source: Student.proto 3 | 4 | package com.shengsiyuan.proto; 5 | 6 | public interface StudentResponseOrBuilder extends 7 | // @@protoc_insertion_point(interface_extends:com.shengsiyuan.proto.StudentResponse) 8 | com.google.protobuf.MessageOrBuilder { 9 | 10 | /** 11 | * string name = 1; 12 | */ 13 | java.lang.String getName(); 14 | /** 15 | * string name = 1; 16 | */ 17 | com.google.protobuf.ByteString 18 | getNameBytes(); 19 | 20 | /** 21 | * int32 age = 2; 22 | */ 23 | int getAge(); 24 | 25 | /** 26 | * string city = 3; 27 | */ 28 | java.lang.String getCity(); 29 | /** 30 | * string city = 3; 31 | */ 32 | com.google.protobuf.ByteString 33 | getCityBytes(); 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/proto/StudentServiceGrpc.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.proto; 2 | 3 | import static io.grpc.stub.ClientCalls.asyncUnaryCall; 4 | import static io.grpc.stub.ClientCalls.asyncServerStreamingCall; 5 | import static io.grpc.stub.ClientCalls.asyncClientStreamingCall; 6 | import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall; 7 | import static io.grpc.stub.ClientCalls.blockingUnaryCall; 8 | import static io.grpc.stub.ClientCalls.blockingServerStreamingCall; 9 | import static io.grpc.stub.ClientCalls.futureUnaryCall; 10 | import static io.grpc.MethodDescriptor.generateFullMethodName; 11 | import static io.grpc.stub.ServerCalls.asyncUnaryCall; 12 | import static io.grpc.stub.ServerCalls.asyncServerStreamingCall; 13 | import static io.grpc.stub.ServerCalls.asyncClientStreamingCall; 14 | import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall; 15 | import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall; 16 | import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall; 17 | 18 | /** 19 | */ 20 | @javax.annotation.Generated( 21 | value = "by gRPC proto compiler (version 1.4.0)", 22 | comments = "Source: Student.proto") 23 | public final class StudentServiceGrpc { 24 | 25 | private StudentServiceGrpc() {} 26 | 27 | public static final String SERVICE_NAME = "com.shengsiyuan.proto.StudentService"; 28 | 29 | // Static method descriptors that strictly reflect the proto. 30 | @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") 31 | public static final io.grpc.MethodDescriptor METHOD_GET_REAL_NAME_BY_USERNAME = 33 | io.grpc.MethodDescriptor.newBuilder() 34 | .setType(io.grpc.MethodDescriptor.MethodType.UNARY) 35 | .setFullMethodName(generateFullMethodName( 36 | "com.shengsiyuan.proto.StudentService", "GetRealNameByUsername")) 37 | .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( 38 | com.shengsiyuan.proto.MyRequest.getDefaultInstance())) 39 | .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( 40 | com.shengsiyuan.proto.MyResponse.getDefaultInstance())) 41 | .build(); 42 | @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") 43 | public static final io.grpc.MethodDescriptor METHOD_GET_STUDENTS_BY_AGE = 45 | io.grpc.MethodDescriptor.newBuilder() 46 | .setType(io.grpc.MethodDescriptor.MethodType.SERVER_STREAMING) 47 | .setFullMethodName(generateFullMethodName( 48 | "com.shengsiyuan.proto.StudentService", "GetStudentsByAge")) 49 | .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( 50 | com.shengsiyuan.proto.StudentRequest.getDefaultInstance())) 51 | .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( 52 | com.shengsiyuan.proto.StudentResponse.getDefaultInstance())) 53 | .build(); 54 | @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") 55 | public static final io.grpc.MethodDescriptor METHOD_GET_STUDENTS_WRAPPER_BY_AGES = 57 | io.grpc.MethodDescriptor.newBuilder() 58 | .setType(io.grpc.MethodDescriptor.MethodType.CLIENT_STREAMING) 59 | .setFullMethodName(generateFullMethodName( 60 | "com.shengsiyuan.proto.StudentService", "GetStudentsWrapperByAges")) 61 | .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( 62 | com.shengsiyuan.proto.StudentRequest.getDefaultInstance())) 63 | .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( 64 | com.shengsiyuan.proto.StudentResponseList.getDefaultInstance())) 65 | .build(); 66 | @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") 67 | public static final io.grpc.MethodDescriptor METHOD_BI_TALK = 69 | io.grpc.MethodDescriptor.newBuilder() 70 | .setType(io.grpc.MethodDescriptor.MethodType.BIDI_STREAMING) 71 | .setFullMethodName(generateFullMethodName( 72 | "com.shengsiyuan.proto.StudentService", "BiTalk")) 73 | .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( 74 | com.shengsiyuan.proto.StreamRequest.getDefaultInstance())) 75 | .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( 76 | com.shengsiyuan.proto.StreamResponse.getDefaultInstance())) 77 | .build(); 78 | 79 | /** 80 | * Creates a new async stub that supports all call types for the service 81 | */ 82 | public static StudentServiceStub newStub(io.grpc.Channel channel) { 83 | return new StudentServiceStub(channel); 84 | } 85 | 86 | /** 87 | * Creates a new blocking-style stub that supports unary and streaming output calls on the service 88 | */ 89 | public static StudentServiceBlockingStub newBlockingStub( 90 | io.grpc.Channel channel) { 91 | return new StudentServiceBlockingStub(channel); 92 | } 93 | 94 | /** 95 | * Creates a new ListenableFuture-style stub that supports unary calls on the service 96 | */ 97 | public static StudentServiceFutureStub newFutureStub( 98 | io.grpc.Channel channel) { 99 | return new StudentServiceFutureStub(channel); 100 | } 101 | 102 | /** 103 | */ 104 | public static abstract class StudentServiceImplBase implements io.grpc.BindableService { 105 | 106 | /** 107 | */ 108 | public void getRealNameByUsername(com.shengsiyuan.proto.MyRequest request, 109 | io.grpc.stub.StreamObserver responseObserver) { 110 | asyncUnimplementedUnaryCall(METHOD_GET_REAL_NAME_BY_USERNAME, responseObserver); 111 | } 112 | 113 | /** 114 | */ 115 | public void getStudentsByAge(com.shengsiyuan.proto.StudentRequest request, 116 | io.grpc.stub.StreamObserver responseObserver) { 117 | asyncUnimplementedUnaryCall(METHOD_GET_STUDENTS_BY_AGE, responseObserver); 118 | } 119 | 120 | /** 121 | */ 122 | public io.grpc.stub.StreamObserver getStudentsWrapperByAges( 123 | io.grpc.stub.StreamObserver responseObserver) { 124 | return asyncUnimplementedStreamingCall(METHOD_GET_STUDENTS_WRAPPER_BY_AGES, responseObserver); 125 | } 126 | 127 | /** 128 | */ 129 | public io.grpc.stub.StreamObserver biTalk( 130 | io.grpc.stub.StreamObserver responseObserver) { 131 | return asyncUnimplementedStreamingCall(METHOD_BI_TALK, responseObserver); 132 | } 133 | 134 | @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { 135 | return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) 136 | .addMethod( 137 | METHOD_GET_REAL_NAME_BY_USERNAME, 138 | asyncUnaryCall( 139 | new MethodHandlers< 140 | com.shengsiyuan.proto.MyRequest, 141 | com.shengsiyuan.proto.MyResponse>( 142 | this, METHODID_GET_REAL_NAME_BY_USERNAME))) 143 | .addMethod( 144 | METHOD_GET_STUDENTS_BY_AGE, 145 | asyncServerStreamingCall( 146 | new MethodHandlers< 147 | com.shengsiyuan.proto.StudentRequest, 148 | com.shengsiyuan.proto.StudentResponse>( 149 | this, METHODID_GET_STUDENTS_BY_AGE))) 150 | .addMethod( 151 | METHOD_GET_STUDENTS_WRAPPER_BY_AGES, 152 | asyncClientStreamingCall( 153 | new MethodHandlers< 154 | com.shengsiyuan.proto.StudentRequest, 155 | com.shengsiyuan.proto.StudentResponseList>( 156 | this, METHODID_GET_STUDENTS_WRAPPER_BY_AGES))) 157 | .addMethod( 158 | METHOD_BI_TALK, 159 | asyncBidiStreamingCall( 160 | new MethodHandlers< 161 | com.shengsiyuan.proto.StreamRequest, 162 | com.shengsiyuan.proto.StreamResponse>( 163 | this, METHODID_BI_TALK))) 164 | .build(); 165 | } 166 | } 167 | 168 | /** 169 | */ 170 | public static final class StudentServiceStub extends io.grpc.stub.AbstractStub { 171 | private StudentServiceStub(io.grpc.Channel channel) { 172 | super(channel); 173 | } 174 | 175 | private StudentServiceStub(io.grpc.Channel channel, 176 | io.grpc.CallOptions callOptions) { 177 | super(channel, callOptions); 178 | } 179 | 180 | @java.lang.Override 181 | protected StudentServiceStub build(io.grpc.Channel channel, 182 | io.grpc.CallOptions callOptions) { 183 | return new StudentServiceStub(channel, callOptions); 184 | } 185 | 186 | /** 187 | */ 188 | public void getRealNameByUsername(com.shengsiyuan.proto.MyRequest request, 189 | io.grpc.stub.StreamObserver responseObserver) { 190 | asyncUnaryCall( 191 | getChannel().newCall(METHOD_GET_REAL_NAME_BY_USERNAME, getCallOptions()), request, responseObserver); 192 | } 193 | 194 | /** 195 | */ 196 | public void getStudentsByAge(com.shengsiyuan.proto.StudentRequest request, 197 | io.grpc.stub.StreamObserver responseObserver) { 198 | asyncServerStreamingCall( 199 | getChannel().newCall(METHOD_GET_STUDENTS_BY_AGE, getCallOptions()), request, responseObserver); 200 | } 201 | 202 | /** 203 | */ 204 | public io.grpc.stub.StreamObserver getStudentsWrapperByAges( 205 | io.grpc.stub.StreamObserver responseObserver) { 206 | return asyncClientStreamingCall( 207 | getChannel().newCall(METHOD_GET_STUDENTS_WRAPPER_BY_AGES, getCallOptions()), responseObserver); 208 | } 209 | 210 | /** 211 | */ 212 | public io.grpc.stub.StreamObserver biTalk( 213 | io.grpc.stub.StreamObserver responseObserver) { 214 | return asyncBidiStreamingCall( 215 | getChannel().newCall(METHOD_BI_TALK, getCallOptions()), responseObserver); 216 | } 217 | } 218 | 219 | /** 220 | */ 221 | public static final class StudentServiceBlockingStub extends io.grpc.stub.AbstractStub { 222 | private StudentServiceBlockingStub(io.grpc.Channel channel) { 223 | super(channel); 224 | } 225 | 226 | private StudentServiceBlockingStub(io.grpc.Channel channel, 227 | io.grpc.CallOptions callOptions) { 228 | super(channel, callOptions); 229 | } 230 | 231 | @java.lang.Override 232 | protected StudentServiceBlockingStub build(io.grpc.Channel channel, 233 | io.grpc.CallOptions callOptions) { 234 | return new StudentServiceBlockingStub(channel, callOptions); 235 | } 236 | 237 | /** 238 | */ 239 | public com.shengsiyuan.proto.MyResponse getRealNameByUsername(com.shengsiyuan.proto.MyRequest request) { 240 | return blockingUnaryCall( 241 | getChannel(), METHOD_GET_REAL_NAME_BY_USERNAME, getCallOptions(), request); 242 | } 243 | 244 | /** 245 | */ 246 | public java.util.Iterator getStudentsByAge( 247 | com.shengsiyuan.proto.StudentRequest request) { 248 | return blockingServerStreamingCall( 249 | getChannel(), METHOD_GET_STUDENTS_BY_AGE, getCallOptions(), request); 250 | } 251 | } 252 | 253 | /** 254 | */ 255 | public static final class StudentServiceFutureStub extends io.grpc.stub.AbstractStub { 256 | private StudentServiceFutureStub(io.grpc.Channel channel) { 257 | super(channel); 258 | } 259 | 260 | private StudentServiceFutureStub(io.grpc.Channel channel, 261 | io.grpc.CallOptions callOptions) { 262 | super(channel, callOptions); 263 | } 264 | 265 | @java.lang.Override 266 | protected StudentServiceFutureStub build(io.grpc.Channel channel, 267 | io.grpc.CallOptions callOptions) { 268 | return new StudentServiceFutureStub(channel, callOptions); 269 | } 270 | 271 | /** 272 | */ 273 | public com.google.common.util.concurrent.ListenableFuture getRealNameByUsername( 274 | com.shengsiyuan.proto.MyRequest request) { 275 | return futureUnaryCall( 276 | getChannel().newCall(METHOD_GET_REAL_NAME_BY_USERNAME, getCallOptions()), request); 277 | } 278 | } 279 | 280 | private static final int METHODID_GET_REAL_NAME_BY_USERNAME = 0; 281 | private static final int METHODID_GET_STUDENTS_BY_AGE = 1; 282 | private static final int METHODID_GET_STUDENTS_WRAPPER_BY_AGES = 2; 283 | private static final int METHODID_BI_TALK = 3; 284 | 285 | private static final class MethodHandlers implements 286 | io.grpc.stub.ServerCalls.UnaryMethod, 287 | io.grpc.stub.ServerCalls.ServerStreamingMethod, 288 | io.grpc.stub.ServerCalls.ClientStreamingMethod, 289 | io.grpc.stub.ServerCalls.BidiStreamingMethod { 290 | private final StudentServiceImplBase serviceImpl; 291 | private final int methodId; 292 | 293 | MethodHandlers(StudentServiceImplBase serviceImpl, int methodId) { 294 | this.serviceImpl = serviceImpl; 295 | this.methodId = methodId; 296 | } 297 | 298 | @java.lang.Override 299 | @java.lang.SuppressWarnings("unchecked") 300 | public void invoke(Req request, io.grpc.stub.StreamObserver responseObserver) { 301 | switch (methodId) { 302 | case METHODID_GET_REAL_NAME_BY_USERNAME: 303 | serviceImpl.getRealNameByUsername((com.shengsiyuan.proto.MyRequest) request, 304 | (io.grpc.stub.StreamObserver) responseObserver); 305 | break; 306 | case METHODID_GET_STUDENTS_BY_AGE: 307 | serviceImpl.getStudentsByAge((com.shengsiyuan.proto.StudentRequest) request, 308 | (io.grpc.stub.StreamObserver) responseObserver); 309 | break; 310 | default: 311 | throw new AssertionError(); 312 | } 313 | } 314 | 315 | @java.lang.Override 316 | @java.lang.SuppressWarnings("unchecked") 317 | public io.grpc.stub.StreamObserver invoke( 318 | io.grpc.stub.StreamObserver responseObserver) { 319 | switch (methodId) { 320 | case METHODID_GET_STUDENTS_WRAPPER_BY_AGES: 321 | return (io.grpc.stub.StreamObserver) serviceImpl.getStudentsWrapperByAges( 322 | (io.grpc.stub.StreamObserver) responseObserver); 323 | case METHODID_BI_TALK: 324 | return (io.grpc.stub.StreamObserver) serviceImpl.biTalk( 325 | (io.grpc.stub.StreamObserver) responseObserver); 326 | default: 327 | throw new AssertionError(); 328 | } 329 | } 330 | } 331 | 332 | private static final class StudentServiceDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier { 333 | @java.lang.Override 334 | public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { 335 | return com.shengsiyuan.proto.StudentProto.getDescriptor(); 336 | } 337 | } 338 | 339 | private static volatile io.grpc.ServiceDescriptor serviceDescriptor; 340 | 341 | public static io.grpc.ServiceDescriptor getServiceDescriptor() { 342 | io.grpc.ServiceDescriptor result = serviceDescriptor; 343 | if (result == null) { 344 | synchronized (StudentServiceGrpc.class) { 345 | result = serviceDescriptor; 346 | if (result == null) { 347 | serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) 348 | .setSchemaDescriptor(new StudentServiceDescriptorSupplier()) 349 | .addMethod(METHOD_GET_REAL_NAME_BY_USERNAME) 350 | .addMethod(METHOD_GET_STUDENTS_BY_AGE) 351 | .addMethod(METHOD_GET_STUDENTS_WRAPPER_BY_AGES) 352 | .addMethod(METHOD_BI_TALK) 353 | .build(); 354 | } 355 | } 356 | } 357 | return result; 358 | } 359 | } 360 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/protobuf/ProtoBufTest.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.protobuf; 2 | 3 | 4 | public class ProtoBufTest { 5 | 6 | public static void main(String[] args) throws Exception { 7 | DataInfo.Student student = DataInfo.Student.newBuilder(). 8 | setName("张三").setAge(20).setAddress("北京").build(); 9 | 10 | byte[] student2ByteArray = student.toByteArray(); 11 | 12 | DataInfo.Student student2 = DataInfo.Student.parseFrom(student2ByteArray); 13 | 14 | System.out.println(student2.getName()); 15 | System.out.println(student2.getAge()); 16 | System.out.println(student2.getAddress()); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/thrift/PersonServiceImpl.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.thrift; 2 | 3 | 4 | import org.apache.thrift.TException; 5 | import thrift.generated.DataException; 6 | import thrift.generated.Person; 7 | import thrift.generated.PersonService; 8 | 9 | public class PersonServiceImpl implements PersonService.Iface { 10 | 11 | @Override 12 | public Person getPersonByUsername(String username) throws DataException, TException { 13 | System.out.println("Got Client Param: " + username); 14 | 15 | Person person = new Person(); 16 | 17 | person.setUsername(username); 18 | person.setAge(20); 19 | person.setMarried(false); 20 | 21 | return person; 22 | } 23 | 24 | @Override 25 | public void savePerson(Person person) throws DataException, TException { 26 | System.out.println("Got Client Param: "); 27 | 28 | System.out.println(person.getUsername()); 29 | System.out.println(person.getAge()); 30 | System.out.println(person.isMarried()); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/thrift/ThriftClient.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.thrift; 2 | 3 | 4 | import org.apache.thrift.protocol.TCompactProtocol; 5 | import org.apache.thrift.protocol.TProtocol; 6 | import org.apache.thrift.transport.TFramedTransport; 7 | import org.apache.thrift.transport.TSocket; 8 | import org.apache.thrift.transport.TTransport; 9 | import thrift.generated.Person; 10 | import thrift.generated.PersonService; 11 | 12 | public class ThriftClient { 13 | 14 | public static void main(String[] args) { 15 | TTransport transport = new TFramedTransport(new TSocket("localhost", 8899), 600); 16 | TProtocol protocol = new TCompactProtocol(transport); 17 | PersonService.Client client = new PersonService.Client(protocol); 18 | 19 | try { 20 | transport.open(); 21 | 22 | Person person = client.getPersonByUsername("张三"); 23 | 24 | System.out.println(person.getUsername()); 25 | System.out.println(person.getAge()); 26 | System.out.println(person.isMarried()); 27 | 28 | System.out.println("-------"); 29 | 30 | Person person2 = new Person(); 31 | 32 | person2.setUsername("李四"); 33 | person2.setAge(30); 34 | person2.setMarried(true); 35 | 36 | client.savePerson(person2); 37 | } catch (Exception ex) { 38 | throw new RuntimeException(ex.getMessage(), ex); 39 | } finally { 40 | transport.close(); 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/shengsiyuan/thrift/ThriftServer.java: -------------------------------------------------------------------------------- 1 | package com.shengsiyuan.thrift; 2 | 3 | 4 | import org.apache.thrift.TProcessorFactory; 5 | import org.apache.thrift.protocol.TCompactProtocol; 6 | import org.apache.thrift.server.THsHaServer; 7 | import org.apache.thrift.server.TServer; 8 | import org.apache.thrift.transport.TFramedTransport; 9 | import org.apache.thrift.transport.TNonblockingServerSocket; 10 | import thrift.generated.PersonService; 11 | 12 | public class ThriftServer { 13 | 14 | public static void main(String[] args) throws Exception { 15 | TNonblockingServerSocket socket = new TNonblockingServerSocket(8899); 16 | THsHaServer.Args arg = new THsHaServer.Args(socket).minWorkerThreads(2).maxWorkerThreads(4); 17 | PersonService.Processor processor = new PersonService.Processor<>(new PersonServiceImpl()); 18 | 19 | arg.protocolFactory(new TCompactProtocol.Factory()); 20 | arg.transportFactory(new TFramedTransport.Factory()); 21 | arg.processorFactory(new TProcessorFactory(processor)); 22 | 23 | TServer server = new THsHaServer(arg); 24 | 25 | System.out.println("Thrift Server Started!"); 26 | 27 | server.serve(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/com/shensiyuan/zerocopy/NewIOClient.java: -------------------------------------------------------------------------------- 1 | package com.shensiyuan.zerocopy; 2 | 3 | import java.io.FileInputStream; 4 | import java.net.InetSocketAddress; 5 | import java.nio.channels.FileChannel; 6 | import java.nio.channels.SocketChannel; 7 | 8 | public class NewIOClient { 9 | 10 | public static void main(String[] args) throws Exception { 11 | SocketChannel socketChannel = SocketChannel.open(); 12 | socketChannel.connect(new InetSocketAddress("localhost", 8899)); 13 | socketChannel.configureBlocking(true); 14 | 15 | String fileName = "/Users/zhanglong/Desktop/spark-2.2.0-bin-hadoop2.7.tgz"; 16 | 17 | FileChannel fileChannel = new FileInputStream(fileName).getChannel(); 18 | 19 | long startTime = System.currentTimeMillis(); 20 | 21 | long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel); 22 | 23 | System.out.println("发送总字节数:" + transferCount + ",耗时: " + (System.currentTimeMillis() - startTime)); 24 | 25 | fileChannel.close(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/com/shensiyuan/zerocopy/NewIOServer.java: -------------------------------------------------------------------------------- 1 | package com.shensiyuan.zerocopy; 2 | 3 | import java.net.InetSocketAddress; 4 | import java.net.ServerSocket; 5 | import java.nio.ByteBuffer; 6 | import java.nio.channels.ServerSocketChannel; 7 | import java.nio.channels.SocketChannel; 8 | 9 | public class NewIOServer { 10 | 11 | public static void main(String[] args) throws Exception{ 12 | InetSocketAddress address = new InetSocketAddress(8899); 13 | 14 | ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); 15 | ServerSocket serverSocket = serverSocketChannel.socket(); 16 | serverSocket.setReuseAddress(true); 17 | serverSocket.bind(address); 18 | 19 | ByteBuffer byteBuffer = ByteBuffer.allocate(4096); 20 | 21 | while (true) { 22 | SocketChannel socketChannel = serverSocketChannel.accept(); 23 | socketChannel.configureBlocking(true); 24 | 25 | int readCount = 0; 26 | 27 | while (-1 != readCount) { 28 | try { 29 | readCount = socketChannel.read(byteBuffer); 30 | } catch (Exception ex) { 31 | ex.printStackTrace(); 32 | } 33 | 34 | byteBuffer.rewind(); 35 | } 36 | } 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/shensiyuan/zerocopy/OldIOClient.java: -------------------------------------------------------------------------------- 1 | package com.shensiyuan.zerocopy; 2 | 3 | import java.io.DataOutputStream; 4 | import java.io.FileInputStream; 5 | import java.io.InputStream; 6 | import java.net.Socket; 7 | 8 | public class OldIOClient { 9 | 10 | public static void main(String[] args) throws Exception { 11 | Socket socket = new Socket("localhost", 8899); 12 | 13 | String fileName = "/Users/zhanglong/Desktop/spark-2.2.0-bin-hadoop2.7.tgz"; 14 | InputStream inputStream = new FileInputStream(fileName); 15 | 16 | DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream()); 17 | 18 | byte[] buffer = new byte[4096]; 19 | long readCount; 20 | long total = 0; 21 | 22 | long startTime = System.currentTimeMillis(); 23 | 24 | while ((readCount = inputStream.read(buffer)) >= 0) { 25 | total += readCount; 26 | dataOutputStream.write(buffer); 27 | } 28 | 29 | System.out.println("发送总字节数: " + total + ", 耗时: " + (System.currentTimeMillis() - startTime)); 30 | 31 | dataOutputStream.close(); 32 | socket.close(); 33 | inputStream.close(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/com/shensiyuan/zerocopy/OldIOServer.java: -------------------------------------------------------------------------------- 1 | package com.shensiyuan.zerocopy; 2 | 3 | import java.io.DataInputStream; 4 | import java.net.ServerSocket; 5 | import java.net.Socket; 6 | 7 | public class OldIOServer { 8 | 9 | public static void main(String[] args) throws Exception { 10 | ServerSocket serverSocket = new ServerSocket(8899); 11 | 12 | while (true) { 13 | Socket socket = serverSocket.accept(); 14 | DataInputStream dataInputStream = new DataInputStream(socket.getInputStream()); 15 | 16 | try { 17 | byte[] byteArray = new byte[4096]; 18 | 19 | while (true) { 20 | int readCount = dataInputStream.read(byteArray, 0, byteArray.length); 21 | 22 | if (-1 == readCount) { 23 | break; 24 | } 25 | } 26 | } catch (Exception ex) { 27 | ex.printStackTrace(); 28 | } 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/proto/Student.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package com.shengsiyuan.proto; 4 | 5 | option java_package = "com.shengsiyuan.proto"; 6 | option java_outer_classname = "StudentProto"; 7 | option java_multiple_files = true; 8 | 9 | service StudentService { 10 | 11 | rpc GetRealNameByUsername(MyRequest) returns (MyResponse) {} 12 | 13 | rpc GetStudentsByAge(StudentRequest) returns (stream StudentResponse) {} 14 | 15 | rpc GetStudentsWrapperByAges(stream StudentRequest) returns (StudentResponseList) {} 16 | 17 | rpc BiTalk(stream StreamRequest) returns (stream StreamResponse) {} 18 | 19 | } 20 | 21 | message MyRequest { 22 | string username = 1; 23 | } 24 | 25 | message MyResponse { 26 | string realname = 2; 27 | } 28 | 29 | message StudentRequest { 30 | int32 age = 1; 31 | } 32 | 33 | message StudentResponse { 34 | string name = 1; 35 | int32 age = 2; 36 | string city = 3; 37 | } 38 | 39 | message StudentResponseList { 40 | repeated StudentResponse studentResponse = 1; 41 | } 42 | 43 | message StreamRequest { 44 | string request_info = 1; 45 | } 46 | 47 | message StreamResponse { 48 | string response_info = 1; 49 | } 50 | 51 | -------------------------------------------------------------------------------- /src/main/resources/log4j.properties: -------------------------------------------------------------------------------- 1 | #log4j.rootLogger=DEBUG, stdout 2 | # 3 | #log4j.appender.stdout=org.apache.log4j.ConsoleAppender 4 | #log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 5 | #log4j.appender.stdout.layout.ConversionPattern=[%p] %C{1} - %m%n -------------------------------------------------------------------------------- /src/protobuf/Person.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto2"; 2 | 3 | package com.shengsiyuan.protobuf; 4 | 5 | option optimize_for = SPEED; 6 | option java_package = "com.shengsiyuan.netty.sixthexample"; 7 | option java_outer_classname = "MyDataInfo"; 8 | 9 | message MyMessage { 10 | 11 | enum DataType{ 12 | PersonType = 1; 13 | DogType = 2; 14 | CatType = 3; 15 | } 16 | 17 | required DataType data_type = 1; 18 | 19 | oneof dataBody { 20 | Person person = 2; 21 | Dog dog = 3; 22 | Cat cat = 4; 23 | } 24 | } 25 | 26 | message Person { 27 | optional string name = 1; 28 | optional int32 age = 2; 29 | optional string address = 3; 30 | } 31 | 32 | message Dog { 33 | optional string name = 1; 34 | optional int32 age = 2; 35 | } 36 | 37 | message Cat { 38 | optional string name = 1; 39 | optional string city = 2; 40 | } 41 | 42 | 43 | -------------------------------------------------------------------------------- /src/thrift/data.thrift: -------------------------------------------------------------------------------- 1 | namespace java thrift.generated 2 | namespace py py.thrift.generated 3 | 4 | typedef i16 short 5 | typedef i32 int 6 | typedef i64 long 7 | typedef bool boolean 8 | typedef string String 9 | 10 | struct Person { 11 | 1: optional String username, 12 | 2: optional int age, 13 | 3: optional boolean married 14 | } 15 | 16 | exception DataException { 17 | 1: optional String message, 18 | 2: optional String callStack, 19 | 3: optional String date 20 | } 21 | 22 | service PersonService { 23 | Person getPersonByUsername(1: required String username) throws (1: DataException dataException), 24 | 25 | void savePerson(1: required Person person) throws (1: DataException dataException) 26 | } 27 | -------------------------------------------------------------------------------- /src/webapp/test.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | WebSocket客户端 6 | 7 | 8 | 9 | 46 | 47 | 48 |
49 | 50 | 51 | 52 | 53 | 54 |

服务端输出:

55 | 56 | 57 | 58 | 59 | 60 |
61 | 62 | 63 | 64 | 65 | --------------------------------------------------------------------------------