簡體   English   中英

兩台計算機之間的套接字編程

[英]Socket programming between two computers

我正在嘗試在兩台計算機之間進行通信,一台是Mac,另一台是Linux。

我在服務器端的代碼:

import os
from socket import *

host = "192.168.1.47"
port = 10000
buf = 1024

address = (host, port)
UDPSock = socket(AF_INET, SOCK_DGRAM)
UDPSock.bind(address)

print ("Waiting to receive messages...")

while True:
    (data, address) = UDPSock.recvfrom(buf)
    print("Received message: " + data)
    if data == "exit":
        break

UDPSock.close()
os._exit(0)

在客戶端,我有:

import os
from socket import *

host = "192.168.1.47" # set to IP address of target computer
port = 10000
addr = (host, port)

UDPSock = socket(AF_INET, SOCK_DGRAM)

while True:
    data = raw_input("Enter message to send or type 'exit': ")
    UDPSock.sendto(data, addr)
    if data == "exit":
        break

UDPSock.close()
os._exit(0)

服務器一直在等待請求,盡管我發送了一些在客戶端服務器中鍵入的消息,但無法接收到該請求。 主機地址是我的Mac IP地址,並要求另一台計算機連接到該IP。 誰能幫助我了解我哪里出了問題。 我提到了與此主題相關的其他帖子,但是沒有合適的解決方案。 謝謝

首先:使用相同的端口:)

並且您正在使用本地主機地址在客戶端上發送消息。 使用客戶端的服務器地址。

對於服務器:

ip =“本地主機”或“服務器ip”

端口= 10000

對於客戶:

ip =“服務器ip”

端口= 10000

它在同一主機上對我有用。 當字符串前有一個“ b”時,是因為我更改了以字節為單位的字符串。

<string> .encode()更改字符串(以字節為單位)

<bytes> .decode()更改字符串中的字節

您需要了解如果使用UDP,則兩台計算機之間沒有連接。 因此,如果您想使用TCP套接字更改該鏈接,防火牆將阻止該鏈接。

我建議您使用python 3,並且打印此語法很酷:

print("{}".format(msg_recv))

您以format(..)添加變量,它們將替換“ {}”。

客戶:

import os
from socket import *

host = "127.0.0.1" # set to IP address of target computer
port = 10000
addr = (host, port)

UDPSock = socket(AF_INET, SOCK_DGRAM)

while True:
    data = input("Enter message to send or type 'exit': ")
    UDPSock.sendto(data.encode(), addr)
    if data == "exit":
        break

UDPSock.close()
os._exit(0)

服務器:

import os
from socket import *

host = "127.0.0.1"
port = 10000
buf = 1024

address = (host, port)
UDPSock = socket(AF_INET, SOCK_DGRAM)
UDPSock.bind(address)

print ("Waiting to receive messages...")

while True:
    (data, address) = UDPSock.recvfrom(buf)
    print("Received message: " + data.decode())
    if data == b"exit":
        break

UDPSock.close()
os._exit(0)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM