Client 소스는 좀더 간단하다. Server의 경우에는 Bind와 Listen의 절차를 거치고, Listen에서 BeginListen, EndListen으로
AsyncCallback을 통해야지 되지만, Client의 경우에는 간단히 Connect만으로 가능하고, 하나의 Client에서는 역시 하나의
연결정도만 신경을 쓰면 되기 때문에 더욱더 편한 개발이 가능하다.
솔찍한 생각으로 예제 소스이긴 하지만, UI단만 조금 붙여버리면 거의 일반 프로그램들과 큰 차이가 안보인다.
Socket의 Close시에 Shutdown으로 Socket을 정리하는 부분에 신경을 쓰면 될 것 같다.
AsyncCallback을 통해야지 되지만, Client의 경우에는 간단히 Connect만으로 가능하고, 하나의 Client에서는 역시 하나의
연결정도만 신경을 쓰면 되기 때문에 더욱더 편한 개발이 가능하다.
솔찍한 생각으로 예제 소스이긴 하지만, UI단만 조금 붙여버리면 거의 일반 프로그램들과 큰 차이가 안보인다.
Socket의 Close시에 Shutdown으로 Socket을 정리하는 부분에 신경을 쓰면 될 것 같다.
001.
/****************************** Module Header ******************************\
002.
* Module Name: Program.cs
003.
* Project: CSSocketClient
004.
* Copyright (c) Microsoft Corporation.
005.
*
006.
* Sockets are an application programming interface(API) in an operating system
007.
* used for in inter-process communication. Sockets constitute a mechanism for
008.
* delivering incoming data packets to the appropriate application process or
009.
* thread, based on a combination of local and remote IP addresses and port
010.
* numbers. Each socket is mapped by the operational system to a communicating
011.
* application process or thread.
012.
*
013.
*
014.
* .NET supplies a Socket class which implements the Berkeley sockets interface.
015.
* It provides a rich set of methods and properties for network communications.
016.
* Socket class allows you to perform both synchronous and asynchronous data
017.
* transfer using any of the communication protocols listed in the ProtocolType
018.
* enumeration. It supplies the following types of socket:
019.
*
020.
* Stream: Supports reliable, two-way, connection-based byte streams without
021.
* the duplication of data and without preservation of boundaries.
022.
*
023.
* Dgram:Supports datagrams, which are connectionless, unreliable messages of
024.
* a fixed (typically small) maximum length.
025.
*
026.
* Raw: Supports access to the underlying transport protocol.Using the
027.
* SocketTypeRaw, you can communicate using protocols like Internet Control
028.
* Message Protocol (Icmp) and Internet Group Management Protocol (Igmp).
029.
*
030.
* Rdm: Supports connectionless, message-oriented, reliably delivered messages,
031.
* and preserves message boundaries in data.
032.
*
033.
* Seqpacket:Provides connection-oriented and reliable two-way transfer of
034.
* ordered byte streams across a network.
035.
*
036.
* Unknown:Specifies an unknown Socket type.
037.
*
038.
* This source is subject to the Microsoft Public License.
039.
* See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
040.
* All other rights reserved.
041.
*
042.
* THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
043.
* EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
044.
* WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
045.
\***************************************************************************/
046.
047.
#region Using directives
048.
using
System;
049.
using
System.Collections.Generic;
050.
using
System.Linq;
051.
using
System.Text;
052.
using
System.Net;
053.
using
System.Net.Sockets;
054.
using
System.Security;
055.
using
System.Security.Permissions;
056.
#endregion
057.
058.
059.
public
class
Program
060.
{
061.
static
void
Main(
string
[] args)
062.
{
063.
// Receiving byte array
064.
byte
[] bytes =
new
byte
[1024];
065.
try
066.
{
067.
// Create one SocketPermission for socket access restrictions
068.
SocketPermission permission =
new
SocketPermission(
069.
NetworkAccess.Connect,
// Connection permission
070.
TransportType.Tcp,
// Defines transport types
071.
""
,
// Gets the IP addresses
072.
SocketPermission.AllPorts
// All ports
073.
);
074.
075.
// Ensures the code to have permission to access a Socket
076.
permission.Demand();
077.
078.
// Resolves a host name to an IPHostEntry instance
079.
IPHostEntry ipHost = Dns.GetHostEntry(
""
);
080.
081.
// Gets first IP address associated with a localhost
082.
IPAddress ipAddr = ipHost.AddressList[0];
083.
084.
// Creates a network endpoint
085.
IPEndPoint ipEndPoint =
new
IPEndPoint(ipAddr, 6000);
086.
087.
// Create one Socket object to setup Tcp connection
088.
Socket sender =
new
Socket(
089.
ipAddr.AddressFamily,
// Specifies the addressing scheme
090.
SocketType.Stream,
// The type of socket
091.
ProtocolType.Tcp
// Specifies the protocols
092.
);
093.
094.
sender.NoDelay =
true
;
// Using the Nagle algorithm
095.
096.
// Establishes a connection to a remote host
097.
sender.Connect(ipEndPoint);
098.
Console.WriteLine(
"Socket connected to {0}"
,
099.
sender.RemoteEndPoint.ToString());
100.
101.
// Sending message
102.
//<client quit=""> is the sign for end of data
103.
string
theMessage =
"Hello World!"
;
104.
byte
[] msg =
105.
Encoding.Unicode.GetBytes(theMessage +
"<client quit="
">"
);
106.
107.
// Sends data to a connected Socket.
108.
int
bytesSend = sender.Send(msg);
109.
110.
// Receives data from a bound Socket.
111.
int
bytesRec = sender.Receive(bytes);
112.
113.
// Converts byte array to string
114.
theMessage = Encoding.Unicode.GetString(bytes, 0, bytesRec);
115.
116.
// Continues to read the data till data isn't available
117.
while
(sender.Available > 0)
118.
{
119.
bytesRec = sender.Receive(bytes);
120.
theMessage += Encoding.Unicode.GetString(bytes, 0, bytesRec);
121.
}
122.
Console.WriteLine(
"The server reply: {0}"
, theMessage);
123.
124.
// Disables sends and receives on a Socket.
125.
sender.Shutdown(SocketShutdown.Both);
126.
127.
//Closes the Socket connection and releases all resources
128.
sender.Close();
129.
}
130.
catch
(Exception ex)
131.
{
132.
Console.WriteLine(
"Exception: {0}"
, ex.ToString());
133.
}
134.
}
135.
}
136.
</client></client>