Raspberry Pi 3 :以WebSocket連線JAVA Tomcat Server


Raspberry Pi端

Step 1 :在樹梅派上安裝Websocket Client
  1. sudo pip install websocket-client

Step 2 :撰寫Script如下
  1. import websocket
  2. import thread,time
  3. import GetIP
  4. def on_message(ws, message):
  5.     print message
  6. def on_error(ws, error):
  7.     print "Some Error %s" % error
  8. def on_close(ws):
  9.     print "Server Closed !"
  10.     ws.close()
  11. def on_open(ws):
  12.     def run(*args):
  13.         ws.send("Drone IP,%s" % rip)
  14.         time.sleep(1)
  15.     thread.start_new_thread(run, ())
  16. if __name__ == "__main__":
  17.     rip = GetIP.get_lan_ip()
  18.     print "ip : %s" % rip>    websocket.enableTrace(True)
  19.     ws = websocket.WebSocketApp("ws://Server的IP:8080/Eclipse專案名稱/websocketendpoint/"+rip,
  20.                                 on_message = on_message,
  21.                                 on_error = on_error,
  22.                                 on_close = on_close)
  23.     ws.on_open = on_open
  24.     ws.run_forever()

Step 3 : GetIP是從網路找到的資源,如下
  1. import os
  2.  
  3. import socket
  4.  
  5.  
  6.  
  7. if os.name != "nt":
  8.  
  9.     import fcntl
  10.  
  11.     import struct
  12.  
  13.  
  14.  
  15.     def get_interface_ip(ifname):
  16.  
  17.         s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  18.  
  19.         return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s',
  20.  
  21.                                 ifname[:15]))[20:24])
  22.  
  23.  
  24.  
  25. def get_lan_ip():
  26.  
  27.     ip = socket.gethostbyname(socket.gethostname())
  28.  
  29.     if ip.startswith("127.") and os.name != "nt":
  30.  
  31.         interfaces = [
  32.  
  33.             "eth0",
  34.  
  35.             "eth1",
  36.  
  37.             "eth2",
  38.  
  39.             "wlan0",
  40.  
  41.             "wlan1",
  42.  
  43.             "wifi0",
  44.  
  45.             "ath0",
  46.  
  47.             "ath1",
  48.  
  49.             "ppp0",
  50.  
  51.             ]
  52.  
  53.         for ifname in interfaces:
  54.  
  55.             try:
  56.  
  57.                 ip = get_interface_ip(ifname)
  58.  
  59.                 break
  60.  
  61.             except IOError:
  62.  
  63.                 pass
  64.  
  65.     return ip

Server端(Windows)

Step 1 :先安裝JAVA

Step 2 :下載Eclipse,解壓縮

Step 3 :下載Tomcat,解壓縮到桌面

Step 4 :下載MySQL(如果Server要建資料庫才需要)

Step 5 :開始安裝環境,執行Eclipse,建立Workspace

Step 6 :Tomcat設定教學文

Step 7 :安裝MySQL時,唯一要注意的是密碼設定要記住(在Accounts and Roles這個步驟),其他都是下一步就好

Step 8 :建立專案,File  >>  New  >>  Dynamic Web Project

Step 9 :設定如下(我使用的Tomcat版本較舊,新的設定一樣)


Step 10 :在src加入一個package,新增一個class

Step 11 :加入測試程式碼如下
  1. import java.io.IOException;
  2. import java.lang.reflect.Type;
  3. import java.nio.ByteBuffer;
  4. import java.sql.SQLException;
  5. import java.util.ArrayList;
  6. import java.util.HashMap;
  7. import java.util.LinkedList;
  8. import java.util.Queue;
  9. import java.util.concurrent.ConcurrentLinkedQueue;
  10. import java.text.DecimalFormat;
  11. import javax.websocket.OnClose;
  12. import javax.websocket.OnError;
  13. import javax.websocket.OnMessage;
  14. import javax.websocket.OnOpen;
  15. import javax.websocket.RemoteEndpoint;
  16. import javax.websocket.Session;
  17. import javax.websocket.server.ServerEndpoint;
  18.  
  19. @ServerEndpoint("/websocketendpoint/{ip}")
  20.  
  21. //從樹梅派接收一個IP字串
  22. public class Server {
  23. @OnOpen
  24. public void onOpen(Session session) throws Exception{
  25.                System.out.print("Server Open\n");
  26. }
  27. @OnClose
  28. public void onClose(Session session){
  29.                System.out.print("Server Close\n");
  30. }
  31. @OnError
  32. public void onError(Session session, Throwable e){
  33.                System.out.print("Something Error\n");
  34. }
  35. @OnMessage
  36. public void onMessage(String message, Session currentSession) throws Exception{
  37. System.out.print(message+"\n");
  38. }
  39. }
  40. }

Step 11 :要執行時,對該java按右鍵  >>  Run As  >>  1 Run on Server  >>  Finish

Step12:此時可執行樹梅派上的python script,測試是否可以執行

注意:

1.如果Server沒有實體IP,記得樹梅派跟Server要在同一個區網

2.Server端如果運作的是Windows OS,記得關閉防火牆,不然延遲非常驚人

留言