1. 程式人生 > 程式設計 >Python3的socket使用方法詳解

Python3的socket使用方法詳解

這篇文章主要介紹了Python3的socket使用方法詳解,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

需要實現兩臺機器的資訊互動,使用 socket 進行排程。其中服務端為:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket

# 服務端ip
server_address = ('192.168.229.129',10000)
# 客戶端ip
client_address = ("192.168.229.130",10000)
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

s.bind(server_address)
while 1:
  data,addr=s.recvfrom(2048)
  if not data:
    break
  print("got data from",addr)
  print(data.decode())
  replydata = input("reply:")
  s.sendto(replydata.encode("utf-8"),client_address)
s.close()

客戶端為:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket

# 服務端ip
server_address = ('192.168.229.129',10000)

s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(client_address)
while 1:
  data = input("input:")
  if not data:
    break
  s.sendto(data.encode("utf-8"),server_address)

  recivedata,addrg = s.recvfrom(2048)
  if recivedata:
    print("from:",addrg)
    print("got recive :",recivedata.decode())
s.close()

啟動過後如下所示:

客戶端傳送:

input:hello world
from: ('192.168.229.129',10000)
got recive : my name is server
input:my name is client,hahaha
from: ('192.168.229.129',10000)
got recive : woca

服務端接收:

got data from ('192.168.229.130',10000)
hello world
reply:my name is server
got data from ('192.168.229.130',10000)
my name is client,hahaha
reply:woca

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。