一些 socket通讯代码

服务器- 接受int  返回 int 

***

#该函数用于开启一个socket服务器,接受来自客户端的 图片大小
def function_socket_receive_picture_size():
     global g_received_picture_size
     listenSocekt=socket(AF_INET, SOCK_STREAM) 
     IP='127.0.0.1'
     PORT=50000
     listenSocekt.bind((IP,PORT))
     listenSocekt.listen(1)#开始监听
     print("Server50000 listening...")
     #开启循环,为客户服务
     while True:
          client_Incarnation , client_ip=listenSocekt.accept()#等客人上门
          with client_Incarnation:#with 的作用是:自动关闭主服务器 socket(防止端口占用)。
               print(f"Connected by {client_ip}")
               # 读取4字节长度(大端序)
               length_data = bytearray()
               while len(length_data) < 4:
                    packet  = client_Incarnation.recv(4 - len(length_data))
                    if not packet :
                        print(f"连接中断,已接收数据长度: {len(length_data)}")
                        break# 连接中断
                    length_data+=packet 
                    print("Invalid length received{packet}")

               if len(length_data) != 4:
                    print("Invalid length received{client_ip}")
                    continue
               # 解析整数(网络字节序)
               g_received_picture_size = struct.unpack('!I', length_data)[0]
               print(f"Received number: {g_received_picture_size}")
               # 将相同数字发回客户端
               client_Incarnation.sendall(struct.pack('!i', g_received_picture_size))
               print(f"Sent back: {g_received_picture_size}")

  ***

  Bitmap bitmapOld = new Bitmap(100, 100);
                        switch (m_picture_no)
                        {
                            case 0:
                                this.Invoke(new Action(() =>
                                {
                                    bitmapOld = pictureBox_test.Image as Bitmap;
                                    pictureBox_test.Image = bitmap;
                                }));
                                break;
                            case 1:
                                this.Invoke(new Action(() =>
                                {
                                    bitmapOld = pictureBox_Camer1_Original.Image as Bitmap;
                                    pictureBox_Camer1_Original.Image = bitmap;
                                }));
                                break;
                            case 2:
                                this.Invoke(new Action(() =>
                                {
                                    bitmapOld = pictureBox_Camer2_Original.Image as Bitmap;
                                    pictureBox_Camer2_Original.Image = bitmap;
                                }));
                                break;
                            default:
                                MessageBox.Show("相机索引错误");
                                break;

                        }

 

posted @ 2025-03-24 14:02  wenluderen  阅读(10)  评论(1)    收藏  举报