Raspberry Pi 3 :以WebSocket連線JAVA Tomcat Server


Raspberry Pi端

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

Step 2 :撰寫Script如下
import websocket
import thread,time
import GetIP
def on_message(ws, message):
    print message
def on_error(ws, error):
    print "Some Error %s" % error
def on_close(ws):
    print "Server Closed !"
    ws.close()
def on_open(ws):
    def run(*args):
        ws.send("Drone IP,%s" % rip)
        time.sleep(1)
    thread.start_new_thread(run, ())
if __name__ == "__main__":
    rip = GetIP.get_lan_ip()
    print "ip : %s" % rip>    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://Server的IP:8080/Eclipse專案名稱/websocketendpoint/"+rip,
                                on_message = on_message,
                                on_error = on_error,
                                on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()

Step 3 : GetIP是從網路找到的資源,如下
import os

import socket



if os.name != "nt":

    import fcntl

    import struct



    def get_interface_ip(ifname):

        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s',

                                ifname[:15]))[20:24])



def get_lan_ip():

    ip = socket.gethostbyname(socket.gethostname())

    if ip.startswith("127.") and os.name != "nt":

        interfaces = [

            "eth0",

            "eth1",

            "eth2",

            "wlan0",

            "wlan1",

            "wifi0",

            "ath0",

            "ath1",

            "ppp0",

            ]

        for ifname in interfaces:

            try:

                ip = get_interface_ip(ifname)

                break

            except IOError:

                pass

    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 :加入測試程式碼如下
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.ByteBuffer;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.text.DecimalFormat;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/websocketendpoint/{ip}")

//從樹梅派接收一個IP字串
public class Server { 
 @OnOpen
 public void onOpen(Session session) throws Exception{
               System.out.print("Server Open\n");
 }
 
 @OnClose
 public void onClose(Session session){
               System.out.print("Server Close\n");
 }
 
 @OnError
 public void onError(Session session, Throwable e){
               System.out.print("Something Error\n");
 }
 
 @OnMessage
 public void onMessage(String message, Session currentSession) throws Exception{
  System.out.print(message+"\n");
  }
 }
}

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

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

注意:

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

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

留言