Python 超简单的聊天程序

我这里实现的是客户端与服务端进行通信的功能,比较简单,与上一篇文章的群聊不太一样。

服务端server.py

#-*- coding:utf-8 -*-
import socket, traceback, sys

host = ''
port = 51423

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((host, port))
s.listen(1)

ClientSock, ClientAddr = s.accept()
while 1:
    try:
        buf = ClientSock.recv(1024)
        if len(buf):
            print "客户端说: " + buf
        data = raw_input("服务端说: ")
        ClientSock.sendall(data)
    except:
        print "Dialogue Over"
        ClientSock.close()
        sys.exit(0)

客户端client.py

#-*- coding:utf-8 -*-
import socket, sys

host = '192.168.80.21'
# host = raw_input("Plz imput destination IP:")
# data = raw_input("Plz imput what you want to submit:")
port = 51423

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

try:
    s.connect((host, port))
except socket.gaierror, e:
    print "Address-related error connecting to server: %s" % e
    sys.exit(1)
except socket.error, e:
    print "Connection error: %s" % e
    sys.exit(1)

while 1:
    try:
        data = raw_input("客户端说: ")
        s.send(data)
        buf = s.recv(1024)
        if len(buf):
            print "服务端说: " + buf
    except:
        print "Dialogue Over"
        s.close()
        sys.exit(0)

结果展示

Python 超简单的聊天程序_第1张图片

Python 超简单的聊天程序_第2张图片

你可能感兴趣的:(Python)