Python socket 编程


server.py

# -*- coding: cp936 -*-
#file:tcpserver.py

import socket
from time import ctime
import sys

bufsize = 1024
host = '127.0.0.1'
port = 8100
address = (host,port)

server_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_sock.bind(address)
server_sock.listen(1)

while True:
    print 'waiting for connection...'
    clientsock,addr = server_sock.accept()
    print 'received from :',addr

    while True:
        data = clientsock.recv(bufsize)
        print ' client:---->%s\n%s' %(ctime(),data)
        data = raw_input("send:----->")
        clientsock.send(data)
    clientsock.close()

server_sock.close()


client.py

## -*- coding: cp936 -*-
##file:tcpclient.py

from socket import *
from time import ctime

bufsize = 1024
host = '127.0.0.1'
port = 8100
addr = (host,port)

client_sock = socket(AF_INET,SOCK_STREAM)
client_sock.connect(addr)

while True:
    data = raw_input("send:---->")
    if not data:
        break
    else:
        client_sock.send(data)
        data = client_sock.recv(bufsize)
        print 'server:---->%s\n%s' %(ctime(),data)

client_sock.close()

效果:

Python socket 编程_第1张图片

你可能感兴趣的:(Python socket 编程)