Python套接字连接示例

时间:2015-08-19 20:04:03

标签: python sockets

我正在写一个简单的套接字程序,但得到以下错误 -

Traceback (most recent call last):
  File "C:\Users\ANAND\workspace\Python_Scratch\Scratch\sockettest.py", line 16, in <module>
    print('Received message == ',s.recv(50))
socket.error: [Errno 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied

socketserver.py

import socket

s = socket.socket()

host = socket.gethostname()

port = 1234

s.bind((host, port))

s.listen(5)

while True:
    c, addr = s.accept()
    print('Got connection from', addr)
    print('Received message == ',s.recv(50))
    c.send('Thank you for connecting')
    c.close()

socketclient.py

import socket
from time import sleep
s = socket.socket()

host = socket.gethostname()

port = 1234

s.connect((host, port))

sleep(10)
s.sendall("Hello!! How are you")
print(s.recv(1024))

1 个答案:

答案 0 :(得分:1)

在socketserver.py中,使用c.recv,而不是s.recv to receive bytes from the connection

print('Received message == ', c.recv(50))

另请注意,只能通过套接字发送字节。因此,如果您使用的是Python3,请务必发送bytes而不是str s:

c.send(b'Thank you for connecting')
s.sendall(b"Hello!! How are you")
import multiprocessing as mp
import socket
import time

def basic():
    sproc = mp.Process(target=server)
    sproc.daemon = True
    sproc.start()
    time.sleep(.5)
    client()
    sproc.join()

def server():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    host = socket.gethostname()
    port = 1234
    s.bind((host, port))
    s.listen(5)
    c, addr = s.accept()
    print('Got connection from {}'.format(addr))
    print('Received message == {}'.format(c.recv(50).decode('ascii')))
    c.send(b'Thank you for connecting')
    c.close()

def client():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = socket.gethostname()
    port = 1234
    s.connect((host, port))
    time.sleep(1)
    s.sendall(b"Hello!! How are you")
    print(s.recv(1024).decode('ascii'))
    s.close()

basic()

产量

Got connection from ('127.0.0.1', 48158)
Received message == Hello!! How are you
Thank you for connecting