Table of Contents

简单的socket代码(包含server,client)

python socket最简单的代码,包含server,client两部分

server.py

pjq@gentoo-pjq ~/workspace/pythonserver $ cat server.py

#!/usr/bin/python

import socket

sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

sock.bind(('localhost',8001))

sock.listen(5)

while True:
  print 'sock.accept'
  connection,address = sock.accept()
  try:
    connection.settimeout(5)
    buf=connection.recv(1024)
    if buf =='1':
      print 'Welcome to server'
      connection.send('Welcome to server') 
    else:
      print 'please go out'
      connection.send('please go out!') 
  except socket.timeout:
    print 'time out'
  print 'connection.close'
  connection.close()

client.py

pjq@gentoo-pjq ~/workspace/pythonserver $ cat client.py

#!/usr/bin/python

import socket 
import time

print 'Create socket'
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)


print 'Connect to server'
sock.connect(('localhost',8001))
time.sleep(2)

print 'Send:1'
sock.send('1')

print 'Recv:'
print sock.recv(1024)

print 'Close socket'
sock.close()