簡單的C# Socket編程

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.