ZengCode.Com (The Thai Php Framework)  


Home   Download   Manual   About us    

Facebook   


MAIN MENU
เขียนโปรแกรมบน iPhone ด้วย MonoTouch
News
Php Tips
Ubuntu
Spring+Strut+Hibernate
Android Programming
Design Pattern By PHP
C# Design Pattern
Linux Quick Tips
C# Tips & Technique
C# using Linq น่าใช้จริงๆ
Java & JavaScript Tips
MAVEN
Database & SQL
ZengCode Framework Guide
Mac OSx
Zeng Code Code
Programming
IPhone (Tips and Trick)

Download เอกสารที่น่าสนใจ

     C# Programming Language » การติดต่อ Socket  (2009-09-10)

การใช้งาน Socket  ที่มา http://codetoday.net/Default.aspx?g=posts&t=281

เมื่อมีการสร้าง Socket ระบบปฏิบัติการจะทำการ allocate พื่อที่ในหน่วยความจำเพื่อสร้างโครงสร้างข้อมูล(Data Structure) สำหรับเก็บข้อมูลที่ใช้สำหรับการสือสารข้อมูล โดย Data Structure นี้ประกอบด้วย Field หลายๆ Field เมื่อ Socket ถูกสร้างขึ้น Field ต่างๆที่อยู่ใน Data Structure นี้จะถูกทำให้ว่างไว้  และโปรแกรมที่สร้าง Socket จะต้องเรียกใช้งาน Function สำหรับใส่ข้อมูลต่างๆที่เว้นว่างไว้ใน Field เหล่านี้
Socket มีหน้าที่สองอย่างคือ การรอรับการเชื่อมต่อและการเชื่อมต่อไปยังเครื่องปลายทาง โดย Socket ที่รอรับการเชื่อมต่อนั้นจะเป็น Socket ที่ใช้ใน Server Application ซึ่งเรียกว่า Passive Socket  และ Socket ที่เชื่อมต่อไปยังเครื่องปลายทางจะถูกใช้ในก Client Application หรือเรียกว่า Active Socket
Socket แบ่งออกได้เป็น 3 แบบได้แก่
1. Datagram Socket หรือ Connectionless Socket
2. Raw Socket
3. Stream Socket หรือ Connection Oriented Socket

ขั้นตอนการสร้าง Passive Socket
จะมีขั้นตอนการสร้างดังนี้
1. Open Socket
2. Name the Socket
3. Listen for incoming connection
4. Accept Client connection
5. Send/Receive Data
6. Close Socket

ขั้นตอนการสร้าง Active Socket
1. Open Socket
2. Connect to Remote Host
3. Send/Receive Data
4. Close Socket

การทำงานเกี่ยวกับ Stream Socket
Stream Socket เป็น Socket ที่ใช้โปรโตคอล TCP ในการสือสารข้อมูล โดยจะแบ่งเป็นสองฝั่งคือ Client และ Server
ตัวอย่างการใช้งาน Stream Socket
วิธีทำเปิด Console Application ขึ้นมาตั้งชื่อว่า SocketApplication ใน project นี้ให้ลบไฟล์ Program.cs ออกแล้วคลิกขวาที่ชื่อ project ->Add->Class ตั้งชื่อไฟล์ว่า SocketServer.cs ซึ่งไฟล์นี้จะทำหน้าที่ในส่วนของ server แล้วเขียนโค้ดตามตัวอย่างด้านล่าง จากนั้น ก็คลิกขวาที่ Solution เลือก Add New project ตั้งชื่อโปรเจกว่า SocketClients จากนั้นลบไฟล์ Program.cs ออกแล้วคลิกขวาที่ชื่อโปรเจคนี้เลือก add->class ตั้งชื่อไฟล์ว่า SocketClient.cs จากนั้นก็เขียนโค้ดตามไฟล์ SocketClient.cs ด้านล่าง พอเขียน ทั้งสองไฟล์เสร็จแล้วก็คลิกขวาที่Solution เลือก Propertiesจากนั้นก็เลือกตรง Radio button ตรง Multiple startup project: เพื่อสั่งให้รัน โปรเจคทางฝั่ง Client และ Server แล้วทั้งสองโปรเจคนี้ให้เลือกตรง Action เป็น Start ดังรูป


 

 

ตัวอย่างโค้ด SocketServer.cs

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Test
{
    class TcpSrvr
    {
        public static void Main()
        {
            int receive;
            byte[] data = new byte[1024];
            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("Connecting to Client");
            Socket client = newsock.Accept();
            string str = "Hello";
            data = Encoding.ASCII.GetBytes(str);
            client.Send(data, data.Length,SocketFlags.None);
            IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;
            Console.WriteLine("Connected with {0} at port {1}", newclient.Address, newclient.Port);
            for (int i = 0; i < 5; i++)
            {
                receive = client.Receive(data);
                Console.WriteLine(Encoding.ASCII.GetString(data, 0, receive));
            }
            Console.WriteLine("Disconnecting from {0}", newclient.Address);
            client.Close();
            newsock.Close();
            Console.ReadLine();
        }
    }
}

ตัวอย่างโค้ด SocketClient.cs

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Test
{
    class TcpClient
    {
        public static void Main()
        {
            byte[] data = new byte[1024];
            string str;
            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.");
            }
            int receive = server.Receive(data);
            str = Encoding.ASCII.GetString(data, 0, receive);
            Console.WriteLine(str);
            Console.WriteLine("Disconnecting from server...");
            server.Shutdown(SocketShutdown.Both);
            server.Close();
            Console.ReadLine();
        }
    }
}

ผลลัพธ์จะได้ดังรูป
 

 


Comment
Name
Comment
Security CodeCAPTCHA Image

web hit counter

This page took 0.055786 seconds to load.