程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 簡單的C# Socket編程(1)

簡單的C# Socket編程(1)

編輯:關於C語言

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved