MatlabWebSocket A simple event-based WebSocket lib开源项目

我要开发同款
匿名用户2021年11月23日
47阅读
所属分类、应用工具、科研计算工具
授权协议MIT License

作品详情

MatlabWebSocket

MatlabWebSocketisasimplelibraryconsistingofawebsocketserverandclientforMATLABbuiltonJava-WebSocket,ajavaimplementationofthewebsocketprotocol.Encryptionissupportedwithself-signedcertificatesmadewiththejavakeytool.

InstallationandUninstallation

IMPORTANT:youmustmakesuretoinstallthejavalibrarytothestaticclasspathbyfollowingtheinstructionsbelow.MatlabWebSocketwillnotworkotherwise!

First,downloadthelatestreleaseonGitHuborMATLABCentralandextractthecontentswhereyouwant.

Therequiredjavalibraryisajarfilelocatedinthe/jar/folder.ItmustbeplacedonthestaticjavaclasspathinMATLAB.Forexample,ifthelocationofthejarfileisC:\MatlabWebSocket\jar\matlab-websocket-*.*.jar,thenopenthestaticclasspathfilewiththefollowingcommand:

edit(fullfile(prefdir,'javaclasspath.txt'))

andaddthelineC:\MatlabWebSocket\jar\matlab-websocket-*.*.jartoit.Makesurethattherearenootherlineswithamatlab-websocket-*entry.

Makesuretoreplacethestarsmatlab-websocket-*.*.jarwiththecorrectversionnumberthatyoudownloaded.

Afterhavingdonethis,restartMATLABandcheckthatthelinewasreadbyMATLABproperlybyrunningthejavaclasspathcommand.Thelineshouldappearatthebottomofthelist,beforetheDYNAMICJAVAPATHentries.NotethatseeingtheentryheredoesnotmeanthatMATLABnecessarilyfoundthejarfileproperly.Youmustmakesurethattheactualjarfileisindeedatthislocation.

Youmustnowaddthe/src/foldertotheMATLABpath.Ifyouwanttoruntheexamples,addthe/examples/folderaswell.

SimplyundotheseoperationstouninstallMatlabWebSocket.

SeetheMATLABDocumentationformoreinformationonthestaticjavaclasspath.

Usage

ToimplementaWebSocketserverorclient,asubclassofeitherWebSocketServerorWebSocketClientmustbedefined.Formoredetails(seetheobject-orientedprogrammingdocumentationofMATLAB).

TheWebSocketServer.mfileisanabstractMATLABclass.Thebehavioroftheservermustthereforebedefinedbycreatingasubclassthatimplementsthefollowingmethods:

onOpen(obj,conn,message)onTextMessage(obj,conn,message)onBinaryMessage(obj,conn,message)onError(obj,conn,message)onClose(obj,conn,message)objistheobjectinstanceofthesubclass,itisimplicitlypassedbyMATLAB(seetheobject-orientedprogrammingdocumentationofMATLAB).messageisthemessagereceivedbytheserver.Itwillusuallybeacharacterarray,exceptfortheonBinaryMessagemethod,inwhichcaseitwillbeanint8arrayconnisaWebSocketConnectionobjectrepresentingtheclientconnectionthatcausedtheevent.Forexample,ifamessageisreceived,theconnobjectwillrepresenttheclientthatsentthismessage.Youcansendmessagestothatclientthroughthisobject.

TheWebSocketClient.mclassisverysimilartotheserver,exceptthatnoconnobjectispassedtotheonSomethingmethods.

Thesemethodswillbeautomaticallycalledwhenthecorrespondingevent(connectionisopened,messagereceived,etc...)occurs.Inthisway,areactivebehaviorcanbedefined.

Theserversupportsavarietyofmethodstohelptalktoclients,lookintheMATLABclassfiletoseewhatmethodsareavailable.

Whenyouaredone,donotforgettodeletetheclientsand/orservers.

SeetheEchoServer.mandSimpleClient.mfilesintheexamplesfolderforanimplementationexample.AgoodresourceonclassesistheMATLABobject-orienteddocumentation.

Example

Theexampleisanechoserver,itreturnstotheclientwhateverwasreceived.

RuntheechoserverbymakingsurethattheexamplefileEchoServer.misontheMATLABpathandexecuting

server=EchoServer(30000)

tostarttheserveronport30000.

Totesttheserver,makeaclientobjectfromtheSimpleClient.mclass:

>>client=SimpleClient('ws://localhost:30000');Connectedtoserveratws://localhost:30000Client1063680447at127.0.0.1:42520openedaconnection

Youcannowconnectandsendmessages(client.send('hi!')).Iftheserverisworkingproperly,youwillreceivemessagesidenticaltotheonesyousend.

Theservercanenumerateclientsthatareconnected,justtype:

server.Connections%viewtheresultasatable:struct2table(server.Connections)

ThisallowsyoutosendamessagetotheclientviaitsidentifyingHashCode:

>>clientCode=server.Connections(1).HashCode;>>server.sendTo(clientCode,'hi,thisistheserver!')Messagereceived:hi,thisistheserver!

Theservercanbestoppedandrestarted(thiswilldisconnectclients):

>>server.stopDisconnectedfromserveratws://localhost:30000

Todeletetheserver,type:

delete(server);clearserver;SSL/WebSocketSecure(wss)

ToenableSSL,youmustfirsthaveacertificate.Aself-signedkeystorecanbegeneratedwiththejavakeytool,butyoushouldalwaysuseavalidcertificateinproduction.Fromthere,opentheserverbypassingthelocationofthestore,thestorepassword,andthekeypassword.WiththeEchoServer,forexample:

PORT=8887;%chooseanotherport!STORE='C:\keystore.jks';STOREPASSWORD='storepassword';KEYPASSWORD='keypassword';s=EchoServer(PORT,STORE,STOREPASSWORD,KEYPASSWORD);

Theclientcanthenconnecttoit:

URI=sprintf(wss://localhost:%d',PORT);c=SimpleClient(URI,STORE,STOREPASSWORD,KEYPASSWORD);

Ifavalidcertificateisused,thedefaultjavakeystorecanbeused.Forexample,wecanconnectaclientdirectlythethesecuredwebsocket.orgtestserver:

>>c2=SimpleClient('wss://echo.websocket.org');Connectedtoserveratwss://echo.websocket.org>>c2.send('hi,thiscommunicationissecured!')Messagereceived:hi,thiscommunicationissecured!BuildingtheJavaJAR

Tobuildthejarfileyourself,itisrecommendedtouseApacheMaven.MavenwillautomaticallytakecareofdownloadingJava-WebSocketandneatlypackageeverythingintoasinglefile(an"uberjar").

Oncethemvncommandisonyourpath,simplycdtothematlab-websocketfolderandexecutemvnpackage.

Acknowledgments

ThisworkwasinspiredbyawebsocketclientMATLABimplementation:matlab-websockets.

ItreliesontheJava-WebSocketlibrary.

License

ThecodeinthisrepositoryislicensedundertheMITlicense.SeetheLICENSEfilefordetails.

声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论