C#Socket

//The Server

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SocketTest
{
 public class Server3
 {
  public Server3()
  {
   
  }
  public void run() {
   string data;
   IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
   Socket newsock = new Socket(AddressFamily.InterNetwork,
    SocketType.Stream, ProtocolType.Tcp);
   newsock.Bind(ipep);
   newsock.Listen(10);
   Console.WriteLine("Waiting for a client...");
   Socket client = newsock.Accept();
   IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;
   Console.WriteLine("Connected with {0} at port {1}",
    newclient.Address, newclient.Port);
   NetworkStream ns = new NetworkStream(client);
   StreamReader sr = new StreamReader(ns);
   StreamWriter sw = new StreamWriter(ns);
   string welcome = "Welcome to my test server";
   sw.WriteLine(welcome);
   sw.Flush();
   while(true) {
    try {
     data = sr.ReadLine();
    } catch (IOException) {
     break;
    }
    Console.WriteLine(data);
    sw.WriteLine(data);
    sw.Flush();
   }
   Console.WriteLine("Disconnected from {0}", newclient.Address);
   sw.Close();
   sr.Close();
   ns.Close();
  }
 }
}

/////////////////////////////////////////////////////////////////////////

//The Client

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SocketTest
{

 public class Client3
 {
  public Client3()
  {
   
  }
  public void run() {
   string data;
   string input;
   IPEndPoint ipep = new IPEndPoint(
    IPAddress.Parse("127.0.0.1"), 9050);
   Socket server = new Socket(AddressFamily.InterNetwork,
    SocketType.Stream, ProtocolType.Tcp);
   try {
    server.Connect(ipep);
   } catch (SocketException e) {
    Console.WriteLine("Unable to connect to server.");
    Console.WriteLine(e.ToString());
    return;
   }
   NetworkStream ns = new NetworkStream(server);
   StreamReader sr = new StreamReader(ns);
   StreamWriter sw = new StreamWriter(ns);
   data = sr.ReadLine();
   Console.WriteLine(data);
   while(true) {
    input = Console.ReadLine();
    if (input == "exit")
     break;
    sw.WriteLine(input);
    sw.Flush();
    data = sr.ReadLine();
    Console.WriteLine(data);
   }
   Console.WriteLine("Disconnecting from server...");
   sr.Close();
   sw.Close();
   ns.Close();
   server.Shutdown(SocketShutdown.Both);
   server.Close();
  }
 }
}

你可能感兴趣的:(socket)