1+ using System ;
2+ using System . IO ;
3+ using System . Net ;
4+ using System . Net . Sockets ;
5+ using System . Text ;
6+
7+ class MyTcpListener
8+ {
9+ public static void Main ( )
10+ {
11+ TcpListener server = null ;
12+ try
13+ {
14+ // Set the TcpListener on port 13000.
15+ Int32 port = 13000 ;
16+ IPAddress localAddr = IPAddress . Parse ( "0.0.0.0" ) ;
17+
18+ // TcpListener server = new TcpListener(port);
19+ server = new TcpListener ( localAddr , port ) ;
20+
21+ // Start listening for client requests.
22+ server . Start ( ) ;
23+
24+ // Buffer for reading data
25+ Byte [ ] bytes = new Byte [ 256 ] ;
26+ String data = null ;
27+
28+ // Enter the listening loop.
29+ while ( true )
30+ {
31+ Console . Write ( "Waiting for a connection... " ) ;
32+
33+ // Perform a blocking call to accept requests.
34+ // You could also use server.AcceptSocket() here.
35+ TcpClient client = server . AcceptTcpClient ( ) ;
36+ Console . WriteLine ( "Connected!" ) ;
37+
38+ data = null ;
39+
40+ // Get a stream object for reading and writing
41+ NetworkStream stream = client . GetStream ( ) ;
42+
43+ int i , b ;
44+ long fileSize ;
45+ string fileName ;
46+
47+ // Loop to receive all the data sent by the client.
48+ while ( ( i = stream . Read ( bytes , 0 , bytes . Length ) ) != 0 )
49+ {
50+ Console . WriteLine ( "i={0}" , i ) ;
51+
52+ // Translate data bytes to a ASCII string.
53+ data = System . Text . Encoding . ASCII . GetString ( bytes , 0 , i ) ;
54+
55+ if ( data . StartsWith ( "@FILE@" ) ) {
56+ fileName = data . Split ( '@' ) [ 2 ] ;
57+ fileSize = int . Parse ( data . Split ( '@' ) [ 3 ] ) ;
58+ Console . WriteLine ( "File Size: {0}, File Name: {1}" , fileSize , fileName ) ;
59+ byte [ ] fileAccept = System . Text . Encoding . ASCII . GetBytes ( "@ACCEPTED@" ) ;
60+ stream . Write ( fileAccept , 0 , fileAccept . Length ) ;
61+
62+ FileStream file = new FileStream ( "./hello.jpg" , FileMode . OpenOrCreate , FileAccess . ReadWrite ) ;
63+ byte [ ] filePacket = new Byte [ 256 ] ;
64+ while ( ( b = stream . Read ( filePacket , 0 , filePacket . Length ) ) != 0 ) {
65+ Console . WriteLine ( "b={0}" , b ) ;
66+
67+ data = System . Text . Encoding . ASCII . GetString ( filePacket , 0 , b ) ;
68+ if ( data == "@SENT@" ) {
69+ Console . WriteLine ( "File Received!" ) ;
70+ } else {
71+ file . Write ( filePacket , 0 , b ) ;
72+ }
73+ }
74+ fileSize = file . Length ;
75+ file . Close ( ) ;
76+
77+ Console . WriteLine ( "File Received!, File Size:{0}" , fileSize ) ;
78+
79+ }
80+ }
81+
82+ // Shutdown and end connection
83+ client . Close ( ) ;
84+ }
85+ }
86+ catch ( SocketException e )
87+ {
88+ Console . WriteLine ( "SocketException: {0}" , e ) ;
89+ }
90+ finally
91+ {
92+ // Stop listening for new clients.
93+ server . Stop ( ) ;
94+ }
95+
96+ Console . WriteLine ( "\n Hit enter to continue..." ) ;
97+ Console . Read ( ) ;
98+ }
99+ }
0 commit comments