python socket ros 多執行緒通訊

2021-10-20 20:08:34 字數 3293 閱讀 2599

採集資料時,鑑於ros之間的通訊需要建立主從節點,對於多台ros之間的通訊暫時還沒找到好的解決方式,故而採用socket進行通訊,相機作為服務端,開多執行緒,接收來自客戶端(ros系統)的資訊。

客戶端的**比較簡單,涉及訂閱相應節點,並將資料傳送給服務端:

// 建立乙個接聽類,用於接收callback返回的資料

class

listener

;char

* listener::

getmessagevalue()

//切記對要返回的變數進行初始化

void listener::

init()

void listener::

socketcallback

(const geometry_msgs::posestampedconstptr& amcl_msg)

;int

main

(int argc,

char

** ar**)

struct sockaddr_in serveraddr;

serveraddr.sin_family = af_inet;

serveraddr.sin_port =

htons

(8888);

serveraddr.sin_addr.s_addr =

inet_addr

("192.168.1.239");

if(connect

(client,

(struct sockaddr*

)&serveraddr,

sizeof

(serveraddr)

)<0)

std::cout <<

"...connect"

<< std::endl;

char buffer[

256]

;while

(ros::ok(

))close

(client)

;return0;

}

服務端是相機,在拍照的同時要保證能接收多個客戶端的訊息,保證**資訊與客戶端資訊一致,部分**如下(相機拍照部分**未貼):

def clientmsg

(client)

: result =

""while true:

data = client.

recv

(1024)[

0:62]

// if判斷是避免獲取到一開始的空資料,並保證留下1條有用資料

if(data and data.

decode

("ascii")[

0]=="b"

or data.

decode

("ascii")[

0]=="r"):

result = data.

decode

("ascii"

)# print(result)

break

return result

//建立執行緒類,用於接收多執行緒通訊的返回結果

class

mythread

(thread)

: def __init__

(self, func, args)

:super

(mythread, self)

.__init__()

self.func = func

self.args = args

def run

(self)

: self.result = self.

func

(*self.args)

def get_result

(self)

:# return self.result

try:

return self.result

except exception:

return none

def getimg()

://獲取**內容省略...

s = socket.

socket()

s.bind

((host, port)

) s.

listen(5

)// 建立多個client,用於接收客戶端資訊

c1, addr = s.

accept()

c2, addr = s.

accept()

c3, addr = s.

accept()

thlist =

while

not rospy.

is_shutdown()

: data =

""//多執行緒接收客戶端資訊,這裡**有待提高,想用for迴圈來著,但是驗證失敗,後續再優化

thread1 =

mythread

(clientmsg, args=

(c1,))

thread2 =

mythread

(clientmsg, args=

(c2,))

thread3 =

mythread

(clientmsg, args=

(c3,))

thlist.

(thread1)

thlist.

(thread2)

thlist.

(thread3)

thread1.

start()

thread2.

start()

thread3.

start()

//join使主線程等待子執行緒完成後再繼續進行,先進行join保證獲取到客戶端的資料,

thread1.

join()

thread2.

join()

thread3.

join()

data1 = thread1.

get_result()

data2 = thread2.

get_result()

data3 = thread3.

get_result()

data = data1 +

" "+ data2 +

" "+ data3 +

" "print

(data)

c1.close()

c2.close()

c3.close

()

JAVA通幽(四)多執行緒

接下來我們進入到多執行緒的學習,向著勝利穩步邁進 1.多執行緒的概念 2.多執行緒實現的方式 package com.jwang.test public class test extends thread public static void main string args package com...

Python高階專題 多執行緒程式設計之執行緒間通訊

執行緒間的通訊在多執行緒程式設計過程中難以避免,常見的執行緒間通訊方式有兩種 共享變數 通過訊息佇列queue實現 1.共享變數 目前接觸的問題來看,適應於解釋多執行緒程式設計過程中乙個典型例項 nums 0def insertnums global nums for i in range 1000...

Linux下基於socket多執行緒併發通訊的實現

編譯伺服器端程式 pthread server.c gcc pthread server.c o server lpthread 編譯客戶端程式 pthread client.c gcc pthread client.c o client 編譯在開發板上跑的客戶端程式 arm linux gcc c...