socket编程之TCP/UDP

Posted 韩德田Tivens

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了socket编程之TCP/UDP相关的知识,希望对你有一定的参考价值。

目标:

  1.编写TCP服务端客户端,实现客户端发送数据,服务端接收打印

  2.采用OOP方式编写TCP服务端客户端,实现客户端发送数据,服务端添加时间戳,返回给客户端

  3.采用OOP方式编写UDP服务端客户端,实现客户端发送数据,服务端添加时间戳,返回给客户端。

 

1.编写TCP服务端客户端,实现客户端发送数据,服务端接收打印

服务端代码如下:

[root@localhost python]# cat tcpserver.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket

host = \'\'
port = 8888
addr = (host,port)


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

while True:
    try:
        cli_sock, cli_addr = s.accept()
    except KeyboardInterrupt:
        break
    print "Client Connected From: ", cli_addr
    while True:
        cli_sock.send("I See You.\\n")
        data = cli_sock.recv(1024)
        if not data.strip():
            break
        print data

    cli_sock.close()
s.close()

客户端代码如下:

[root@localhost python]# cat tcpclient.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket

host = \'\'
port = 8888
addr = (host, port)

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

while True:
    print c.recv(1024),
    data = raw_input("> ")
    if not data.strip():
        break
    c.send(\'%s\\n\' % data)

c.close()

•运行代码,测试效果

 

2.采用OOP方式编写TCP服务端客户端,实现客户端发送数据,服务端添加时间戳,返回给客户端

服务端代码如下:

[root@localhost python]# cat tcptimeserv.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
import time

class TcpTimeServ(object):
    def __init__(self, host, port):
        self.addr = (host, port)
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.s.bind(self.addr)
        self.s.listen(1)

    def handle_child(self, c_sock):
        while True:
            data = c_sock.recv(1024)
            if not data.strip():
                break
            c_sock.send("[%s] %s\\n" %(time.ctime(), data))


    def mainloop(self):
        while True:
            try:
                cli_sock, cli_addr = self.s.accept()
            except KeyboardInterrupt:
                break
            print "Client Connected From: %s", cli_addr
            self.handle_child(cli_sock)
            cli_sock.close()
        self.s.close()



if __name__ == "__main__":
    tcpserv = TcpTimeServ(\'0.0.0.0\', 8888)
    tcpserv.mainloop()

客户端代码如下:

[root@localhost python]# cat tcptimecli.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
import sys

class TcpTimeCli(object):
    def __init__(self, host, port):
        self.addr = (host, port)
        self.c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.c.connect(self.addr)


    def mainloop(self):
        while True:
            data = raw_input("> ").strip()
            if not data:
                break
            self.c.send("%s" % data)
            print self.c.recv(1024)
        self.c.close()


if __name__ == "__main__":
    host = sys.argv[1]
    port = int(sys.argv[2])
    tcpcli = TcpTimeCli(host, port)
    tcpcli.mainloop()

•运行代码,测试效果

 

3.采用OOP方式编写UDP服务端客户端,实现客户端发送数据,服务端添加时间戳,返回给客户端。

服务端代码如下:

 [root@localhost python]# cat udpserver.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
import time


class UdpServ(object):
    def __init__(self, host, port):
        self.addr = (host, port)
        self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.s.bind(self.addr)


    def mainloop(self):
        while True:
            data, cli_addr = self.s.recvfrom(1024)
            data = data.strip()
            self.s.sendto(\'[%s] %s\\n\' %(time.ctime(), data), cli_addr)
        self.close()


if __name__ == "__main__":
    host = \'\'
    port = 8888
    udpserv = UdpServ(host, port)
    udpserv.mainloop()

客户端代码如下:

[root@localhost python]# cat udpclient.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
import sys

class UdpCli(object):
    def __init__(self, host, port):
        self.addr = (host, port)
        self.c = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)


    def mainloop(self):
        while True:
            data = raw_input("> ").strip()
            if not data:
                break
            self.c.sendto("%s\\n" % data, self.addr)
            print self.c.recvfrom(1024)[0]
        self.c.close()


if __name__ == "__main__":
    host = sys.argv[1]
    port = int(sys.argv[2])
    udpcli = UdpCli(host, port)
    udpcli.mainloop()

•运行代码,测试效果

 

以上是关于socket编程之TCP/UDP的主要内容,如果未能解决你的问题,请参考以下文章

网络编程TCP/UDP(socket编程)

Python之UDP编程

python socket编程tcp/udp俩连接

Linux:UDP Socket编程(代码实战)

Linux:UDP Socket编程(代码实战)

网络编程基础之TCP编程学习