Server,服务器代码。
使用Socket套接字连接。
1 using System;
2 using System.Net;
3 using System.Net.Sockets;
4 using System.IO ;
5
6 public class Echoserver
7 {
8 //entry point of main method.
9 public static void Main()
10 {
11 //TcpListener is listening on the given port
12 Int32 port = 1234;
13
14 //IPAddress is connetct ip address
15 //IPAddress addr = IPAddress.Parse("127.0.0.1");
16 IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
17
18 TcpListener tcpListener = new TcpListener(ipAddress,port);
19 tcpListener.Start();
20 Console.WriteLine("Server Started") ;
21 //Accepts a new connection
22 Socket socketForClient = tcpListener.AcceptSocket();
23 //StreamWriter and StreamReader Classes for reading and writing the data to and from.
24 //The server reads the meassage sent by the Client ,converts it to upper case and sends it back to the client.
25 //Lastly close all the streams.
26 try
27 {
28 if (socketForClient.Connected)
29 {
30 while(true)
31 {
32 Console.WriteLine("Client connected");
33 NetworkStream networkStream = new NetworkStream(socketForClient);
34 StreamWriter streamWriter = new StreamWriter(networkStream);
35 StreamReader streamReader = new StreamReader(networkStream);
36 string line = streamReader.ReadLine();
37 Console.WriteLine("Read:" +line);
38 line=line.ToUpper()+ "!";
39 streamWriter.WriteLine(line);
40 Console.WriteLine("Wrote:"+line);
41 streamWriter.Flush() ;
42 }
43 }
44 socketForClient.Close();
45 Console.WriteLine("Exiting");
46 }
47 catch(Exception e)
48 {
49 Console.WriteLine(e.ToString()) ;
50 }
51 }
52}
53
54