套接字超时和连接持续时间超过规定的时间

时间:2016-04-26 15:48:35

标签: c# python sockets

我是Python,C#和套接字编程的新手。我有一台服务器将数据发送到C#客户端。在将所有数据同时发送到当前可用的客户端之后,我想关闭套接字并停止等待连接。如果等待连接超过2分钟,我还想关闭套接字。我已经阅读了Python中的套接字选择工具,但我不确定这是否是在这种情况下使用的正确工具以及如何应用它。

这是我的服务器代码:

import socket #for sockets
import sys #for exit
import select
import struct
import binascii
import time
from thread import *

HOST = "192.168.137.99" # IP address of RPi
PORT = 8888 # arbitrary non privileged port
#create a TCP stream = SOCK_STREAM, AF_INET is IPv4
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

try:
    s.bind((HOST,PORT))
except socket.error, msg:
    print 'Failed to create socket, Error code: ' + str(msg[0]) + ', Error      Error Message : ' + msg[1]
    sys.exit();

print 'Socket bind complete'
s.listen(5)
print 'Socket now listening'
timeout = time.time() + 60
print 'Time now is ' + str(time.time()) + ' and timeout is ' + str(timeout)

strarray = ["0x31\n" "0x31\n" "0x30\n" "0x30\n" "0x31\n" "s\n"] #example data

def clientthread(conn):
    #sending message to connected client
    conn.send('Welcome to server\n')
    for i in range(len(strarray)):
            #packet = struct.pack('1B',1)
            string = strarray[i]
            datas = string.encode()
            conn.send(datas)

    conn.shutdown(2)
    conn.close()

while 1:
    # wait to accept connection
    conn ,addr = s.accept()
    #display client info
    print 'Connected with ' + addr[0] + ': ' + str(addr[1])
    #start new thread takes 1st argument as function name to be run, 2nd is$
    start_new_thread(clientthread ,(conn,))

print 'Closing socket now'
s.close()

这是C#客户端代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;

namespace sockclient_cs
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                TcpClient tcpclnt = new TcpClient();
                Console.WriteLine("Connecting...");
                tcpclnt.Connect("192.168.137.99", 8888);
                Console.WriteLine("Connected");
                NetworkStream stream = tcpclnt.GetStream();
                byte[] first = new byte[80];
                int k = stream.Read(first, 0, 80);
                for (int i = 0; i < k; i++)
                Console.Write(Convert.ToChar(first[i]));
                bool noexit = true;
                while (noexit)
                {

                    Byte[] bb = new byte[1];
                    String responseData = String.Empty;

                    int bytes = stream.Read(bb, 0, bb.Length);
                    ASCIIEncoding ascii = new ASCIIEncoding();
                    responseData = ascii.GetString(bb, 0, bytes);
                    if (responseData == "s")
                    {
                        noexit = false;
                    }
                    Console.Write(responseData);

                }

                tcpclnt.Close();

            }
            catch (Exception e)
            {
                Console.WriteLine("Error...." + e.StackTrace);
            }
        }
    }
}

以下是客户端和服务器输出的屏幕截图:

服务器 - 如您所见,代码永远不会终止:

enter image description here

客户 - 在这种情况下,输出令人满意:

enter image description here

0 个答案:

没有答案