码迷,mamicode.com
首页 > 编程语言 > 详细

python socket 交互通信

时间:2016-05-23 01:03:42      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:python

事例1:

服务端:

#!/usr/bin/env python
# encoding: utf-8

"""
@version: ??
@author: phpergao
@license: Apache Licence 
@file: socket_server.py
@time: 2016-05-22 19:22
"""

import socket
ip_port=("127.0.0.1",9999)
sk=socket.socket()
sk.bind(ip_port)
sk.listen(5)
while True:
    print("server waiting")
    conn,addr=sk.accept()
    client_data=conn.recv(1024)
    print(str(client_data,encoding="utf-8"))
    conn.sendall(bytes("不要回答,我不想被占领",encoding="utf-8"))
    conn.close()

客户端:

import socket
ip_port=("127.0.0.1",9999)
sk=socket.socket()
sk.connect(ip_port)

sk.sendall(bytes("请求占领地球",encoding="utf-8"))
sk.sendall(bytes("\n我要开始侵略占领地球了",encoding="utf-8"))
server_reply=sk.recv(1024)
print(str(server_reply,encoding="utf-8"))
sk.close()

事例2:

服务端:

import socket
ip_port=("127.0.0.1",9999)
sk=socket.socket()
sk.bind(ip_port)
sk.listen(5)
while True:

    print("server waiting")
    conn,addr=sk.accept()
    client_data=conn.recv(1024)
    print(str(client_data,encoding="utf-8"))
    conn.sendall(bytes("不要回答,我不想被占领",encoding="utf-8"))
    while True:
        try:
            client_data=conn.recv(1024)
            print(str(client_data,encoding="utf-8"))
        except Exception:
            print("client close.")
            break
        conn.send(client_data)
    conn.close()

客户端:

import socket
ip_port=("127.0.0.1",9999)
sk=socket.socket()
sk.connect(ip_port)

sk.sendall(bytes("请求占领地球",encoding="utf-8"))
sk.sendall(bytes("\n我要开始侵略占领地球了",encoding="utf-8"))
server_reply=sk.recv(1024)
print(str(server_reply,encoding="utf-8"))
while True:
    enter=input("enter:")
    sk.send(bytes(enter,encoding="utf-8"))
sk.close()

在Linux服务端:

import socket
ip_port=("127.0.0.1",9999)
sk=socket.socket()
sk.bind(ip_port)
sk.listen(5)
while True:

    print("server waiting")
    conn,addr=sk.accept()
    client_data=conn.recv(1024)
    print(str(client_data,encoding="utf-8"))
    conn.sendall(bytes("不要回答,我不想被占领",encoding="utf-8"))
    while True:

        client_data=conn.recv(1024)
        print(str(client_data,encoding="utf-8"))

        if not client_data:
            break
        conn.send(client_data)
    conn.close()


python socket 交互通信

标签:python

原文地址:http://9272317.blog.51cto.com/9262317/1776024

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!