Python中用socket编写服务器和客户端。。。
先说下我的问题,本来预想是,客户端连上服务器,然后向服务器发送信息,服务器再把接收的内容输出。但是貌似服务器在接收连接后就和客户端断开了,不能接收到信息:Tracebac...
先说下我的问题,本来预想是,客户端连上服务器,然后向服务器发送信息,服务器再把接收的内容输出。
但是貌似服务器在接收连接后就和客户端断开了,不能接收到信息:
Traceback (most recent call last):
File "/Users/summer/PycharmProjects/NewL/Server.py", line 18, in <module>
buf = s.recv(1024)
socket.error: [Errno 57] Socket is not connected
这是服务器代码:
#!/usr/bin/env python'
# -*- coding: utf-8 -*-
import socket
host = ''
port = 8080
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(3)
while 1:
conn, addr = s.accept()
print conn, addr
while 1:
buf = s.recv(1024)
if buf is '':
print 'over'
break
print buf
s.close()
这是客户端代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import sys
host = ''
port = 8080
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
raise
except:
print 'fail to create new socket'
sys.exit(1)
try:
s.connect((host, port))
except socket.gaierror:
print 'wrong computer name'
sys.exit(1)
except socket.error:
print 'wrong server'
sys.exit(1)
buf = '*'*34
try:
s.sendall(buf)
except socket.error:
print 'fail to send message'
sys.exit(1)
try:
s.shutdown(1)
except socket.error:
print 'fail to send message all'
sys.exit(1)
s.close()
新手,求教求教 展开
但是貌似服务器在接收连接后就和客户端断开了,不能接收到信息:
Traceback (most recent call last):
File "/Users/summer/PycharmProjects/NewL/Server.py", line 18, in <module>
buf = s.recv(1024)
socket.error: [Errno 57] Socket is not connected
这是服务器代码:
#!/usr/bin/env python'
# -*- coding: utf-8 -*-
import socket
host = ''
port = 8080
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(3)
while 1:
conn, addr = s.accept()
print conn, addr
while 1:
buf = s.recv(1024)
if buf is '':
print 'over'
break
print buf
s.close()
这是客户端代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import sys
host = ''
port = 8080
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error:
raise
except:
print 'fail to create new socket'
sys.exit(1)
try:
s.connect((host, port))
except socket.gaierror:
print 'wrong computer name'
sys.exit(1)
except socket.error:
print 'wrong server'
sys.exit(1)
buf = '*'*34
try:
s.sendall(buf)
except socket.error:
print 'fail to send message'
sys.exit(1)
try:
s.shutdown(1)
except socket.error:
print 'fail to send message all'
sys.exit(1)
s.close()
新手,求教求教 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询