我如何模拟tcp同时打开和关闭状态?

时间:2016-02-11 19:08:41

标签: tcp network-programming tcp-ip simultaneous

我正在学习TCP IP协议。我希望在实践中看到同时开启,关闭,半开/关等条件。我创建了简单的TCP服务器和客户端程序。如何模拟同时打开/关闭,半开/关状态?就像在两者之间进行睡眠,控制-c等等我正在使用' netstat'查看TCP数据包。可以在同一台机器上模拟(服务器和客户端都将运行)吗?

由于

2 个答案:

答案 0 :(得分:0)

我只模拟tcp同时关闭:

server.py:

import socket
import sys

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('127.0.0.5', 10000)
#print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)

while True:
    # Wait for a connection
    #print >>sys.stderr, 'waiting for a connection'
    connection, client_address = sock.accept()
    connection.close()

client.py:

import socket
import sys
import Queue, threading, logging

def do_client():
    # Create a TCP/IP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Connect the socket to the port where the server is listening
    server_address = ('127.0.0.5', 10000)
    #print >>sys.stderr, 'connecting to %s port %s' % server_address
    sock.connect(server_address)
    sock.close()

class WorkManager(object):
    def __init__(self, work_num=100,thread_num=10):
        self.work_queue = Queue.Queue()
        self.threads = []
        self.__init_work_queue(work_num)
        self.__init_thread_pool(thread_num)

    def __init_thread_pool(self,thread_num):
        for i in range(thread_num):
            self.threads.append(Work(self.work_queue))

    def __init_work_queue(self, work_num):
        for i in range(work_num):
            self.add_job(do_job, i)

    def add_job(self, func, args):
        self.work_queue.put((func, args))

    def check_queue(self):
        return self.work_queue.qsize()

    def wait_allcomplete(self):
        for item in self.threads:
            if item.isAlive():item.join()

class Work(threading.Thread):
    def __init__(self, work_queue):
        threading.Thread.__init__(self)
        self.work_queue = work_queue
        self.start()
    def run(self):

        while True:
            try:
                do, args = self.work_queue.get(block=False)
                #print do, args
                do(args)
                self.work_queue.task_done()
            except Exception,e:
                print str(e)
                break

def do_job(args):
    #print args
    do_client()
    #print threading.current_thread(), args

if __name__ == '__main__':
    work_manager =  WorkManager(100, 10)
    work_manager.wait_allcomplete()

我在winodws7上测试过,发现tcp同时关闭如下:

http://developer.android.com/guide/components/services.html

答案 1 :(得分:-1)

要完全控制TCP会话设置等,一种方法是制作自己的TCP / IP数据包并使用原始套接字发送。这是一项工作,但您必须确切地了解如何构建TCP / IP数据包,这样才能获得良好的学习体验。