MatlabWebSocketisasimplelibraryconsistingofawebsocketserverandclientforMATLABbuiltonJava-WebSocket,ajavaimplementationofthewebsocketprotocol.Encryptionissupportedwithself-signedcertificatesmadewiththejavakeytool.
InstallationandUninstallationIMPORTANT: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.
UsageToimplementaWebSocketserverorclient,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.
ExampleTheexampleisanechoserver,itreturnstotheclientwhateverwasreceived.
RuntheechoserverbymakingsurethattheexamplefileEchoServer.misontheMATLABpathandexecuting
server=EchoServer(30000)tostarttheserveronport30000.
Totesttheserver,makeaclientobjectfromtheSimpleClient.mclass:
>>client=SimpleClient('ws://localhost:30000');Connectedtoserveratws://localhost:30000Client1063680447at127.0.0.1:42520openedaconnectionYoucannowconnectandsendmessages(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:30000Todeletetheserver,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!BuildingtheJavaJARTobuildthejarfileyourself,itisrecommendedtouseApacheMaven.MavenwillautomaticallytakecareofdownloadingJava-WebSocketandneatlypackageeverythingintoasinglefile(an"uberjar").
Oncethemvncommandisonyourpath,simplycdtothematlab-websocketfolderandexecutemvnpackage.
AcknowledgmentsThisworkwasinspiredbyawebsocketclientMATLABimplementation:matlab-websockets.
ItreliesontheJava-WebSocketlibrary.
LicenseThecodeinthisrepositoryislicensedundertheMITlicense.SeetheLICENSEfilefordetails.
评论