1. 程式人生 > >C#最基本的Socket程式設計

C#最基本的Socket程式設計

客戶端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {

            int port = 2000;
            string host = "127.0.0.1"
; IPAddress ip = IPAddress.Parse(host); IPEndPoint ipe = new IPEndPoint(ip, port); Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); c.Connect(ipe); string sendStr; sendStr = Console.ReadLine
(); byte[] bs = Encoding.ASCII.GetBytes(sendStr); Console.WriteLine("傳送資訊"); c.Send(bs, bs.Length, 0); string rcvStr = ""; byte[] rcvBytes = new byte[1024]; int bytes = c.Receive(rcvBytes, rcvBytes.Length, 0); rcvStr += Encoding.ASCII
.GetString(rcvBytes, 0, bytes); Console.WriteLine("client get message:{0}", rcvStr); c.Close(); Console.WriteLine("Press Enter to Exit"); Console.ReadKey(); } } }

服務端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int port = 2000;
            string host = "127.0.0.1";

            IPAddress ip = IPAddress.Parse(host);
            IPEndPoint ipe = new IPEndPoint(ip, port);

            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            s.Bind(ipe);
            s.Listen(0);
            Console.WriteLine("等待客戶端連線");

            Socket temp = s.Accept();
            Console.WriteLine("建立連線");
            string rcvStr = "";
            byte[] rcvBytes = new byte[1024];
            int bytes = temp.Receive(rcvBytes, rcvBytes.Length, 0);
            rcvStr += Encoding.ASCII.GetString(rcvBytes, 0, bytes);
            Console.WriteLine("Server get message :{0}", rcvStr);


            string sendStr = "ok!Client send message successful!";
            byte[] bs = Encoding.ASCII.GetBytes(sendStr);
            temp.Send(bs, bs.Length, 0);
            temp.Close();
            s.Close();
            Console.ReadKey();

        }
    }
}