socket 网络编程

一、服务端

import socket
sk = socket.socket()
sk.bind(('127.0.0.1',9999,))
sk.listen(5)

while True:
    conn,address = sk.accept()
    conn.sendall(bytes('欢迎致电10086',encoding='utf-8'))
    while True:
        ret_bytes = conn.recv(1024)
        ret_str = str(ret_bytes,encoding='utf-8')
        if ret_str =='q':
            break
        conn.sendall(bytes(ret_str + 'ok',encoding='utf-8'))

二、客户端

import socket
obj = socket.socket()
obj.connect(('127.0.0.1',9999,))

rec_bytes = obj.recv(1024)
rec_str = str(rec_bytes,encoding='utf-8')
print(rec_str)
while True:
    inp = input('请输入要发送的内容:')
    if inp =='q':
        obj.sendall(bytes(inp,encoding='utf-8'))
        break
    else:
        obj.sendall(bytes(inp, encoding='utf-8'))
        ret = str(obj.recv(1024),encoding='utf-8')
        print(ret)
obj.close()

三、服务端传输文件

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import socket
 4 sk = socket.socket()
 5 sk.bind(('127.0.0.1',9999,))
 6 sk.listen(5)
 7 
 8 while True:
 9     conn,address = sk.accept()
10     conn.sendall(bytes('欢迎登陆FTP系统',encoding='utf-8'))
11     # 先接受文件大小
12     file_size = str(conn.recv(1024),encoding='utf-8')
13     # 与客户端交互,发送响应,解决缓冲区粘包的问题
14     conn.sendall(bytes('传输ok', encoding='utf-8'))
15     total_size = int(file_size)
16     has_recv = 0
17     f = open('new.jpg','wb')
18     # 接收文件直到完毕
19     while True:
20         if total_size ==has_recv:
21             break
22         data = conn.recv(1024)
23         f.write(data)
24         has_recv +=len(data)
25     f.close()

 

四、客户端发送文件

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 import socket
 5 import os
 6 obj = socket.socket()
 7 obj.connect(('127.0.0.1',9999,))
 8 
 9 rec_bytes = obj.recv(1024)
10 rec_str = str(rec_bytes,encoding='utf-8')
11 print(rec_str)
12 
13 # 发送当前文件大小
14 size = os.stat('file.jpg').st_size
15 obj.sendall(bytes(str(size),encoding='utf-8'))
16 # 与服务端交互,解决缓冲区粘包的问题
17 obj.recv(1024)
18 # 发送文件
19 with open('file.jpg','rb') as f:
20     for line in f:
21         obj.sendall(line)
22 obj.close()

 

posted @ 2017-02-26 17:54  Erick-LONG  阅读(175)  评论(0编辑  收藏  举报