1+ using System ;
2+ using System . Collections . Generic ;
3+ using System . Diagnostics ;
4+ using System . IO ;
5+ using System . Linq ;
6+ using System . Net . Sockets ;
7+ using System . Text ;
8+ using System . Threading ;
9+ using System . Threading . Tasks ;
10+
11+ namespace TCPClient
12+ {
13+ class Program
14+ {
15+ static void Main ( string [ ] args )
16+ {
17+ ThreadPool . SetMinThreads ( 100 , 100 ) ;
18+ ThreadPool . SetMaxThreads ( 200 , 200 ) ;
19+
20+ Parallel . For ( 1 , 10 , x =>
21+ {
22+ SendData ( "Tom" ) ;
23+ } ) ;
24+
25+ Console . WriteLine ( "All Completed!" ) ;
26+ Console . ReadKey ( ) ;
27+ }
28+
29+ private static void SendData ( string Name )
30+ {
31+ Task . Run ( ( ) =>
32+ {
33+ Console . WriteLine ( "Start" ) ;
34+ TcpClient tcpClient = new TcpClient ( ) ;
35+ tcpClient . Connect ( "127.0.0.1" , 9000 ) ;
36+ Console . WriteLine ( "Connected" ) ;
37+ NetworkStream netStream = tcpClient . GetStream ( ) ;
38+
39+ Task . Run ( ( ) =>
40+ {
41+ Thread . Sleep ( 100 ) ;
42+ while ( true )
43+ {
44+ if ( ! tcpClient . Client . Connected )
45+ {
46+ break ;
47+ }
48+
49+ if ( netStream == null )
50+ {
51+ break ;
52+ }
53+
54+ try
55+ {
56+ if ( netStream . DataAvailable )
57+ {
58+ byte [ ] data = new byte [ 1024 ] ;
59+ int len = netStream . Read ( data , 0 , 1024 ) ;
60+ var message = Encoding . UTF8 . GetString ( data , 0 , len ) ;
61+ Console . WriteLine ( message ) ;
62+ }
63+ }
64+ catch
65+ {
66+ break ;
67+ }
68+
69+ Thread . Sleep ( 10 ) ;
70+ }
71+ } ) ;
72+
73+ for ( int i = 0 ; i < 100 ; i ++ )
74+ {
75+ byte [ ] datas = Encoding . UTF8 . GetBytes ( Name ) ;
76+ int Len = datas . Length ;
77+ netStream . Write ( datas , 0 , Len ) ;
78+ Thread . Sleep ( 1000 ) ;
79+ }
80+
81+ netStream . Close ( ) ;
82+ netStream = null ;
83+ tcpClient . Close ( ) ;
84+
85+ Console . WriteLine ( "Completed" ) ;
86+ } ) ;
87+ }
88+ }
89+ }
0 commit comments