Magic_kit
2009. 9. 15. 19:13
using System;
using System.Net.Sockets;
using System.Net
using System.Text;
public class SocketServer{
public static void Main (string [] args)
{
IPHostEntry ipHost = Dns.Resolve("localhost");
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 11000);
Socket sListener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
try {
sListener.Bind(ipEndPoint);
sListener.Listen(10);
while (true) {
Console.WriteLine("Waiting for a connection on port {0}",ipEndPoint);
Clientsoket handler = sListener.Accept();
string data = null;
while(true) {
byte[] bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,0,bytesRec);
if (data.IndexOf("") > -1)
{
break;
}
}
Console.WriteLine("Text Received: {0}",data);
string theReply = "Thank you for those " + data.Length.ToString() + " characters...";
byte[] msg = Encoding.ASCII.GetBytes(theReply);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch(Exception e) {
Console.WriteLine(e.ToString());
}
}
} |
using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
public class SocketClient{
public static void Main (string [] args)
{
byte[] bytes = new byte[1024];
try{
IPHostEntry ipHost = Dns.Resolve("127.0.0.1");
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 11000);
Socket sender = new Socket
(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
sender.Connect(ipEndPoint);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
string theMessage;
if (args.Length==0)
theMessage = "This is a test";
else
theMessage = args[0];
byte[] msg = Encoding.ASCII.GetBytes(theMessage+"");
int bytesSent = sender.Send(msg);
int bytesRec = sender.Receive(bytes);
Console.WriteLine("The Server says : {0}",
Encoding.ASCII.GetString(bytes,0, bytesRec));
Sender.Shutdown(SocketShutdown.Both);
sender.Close();
} catch(Exception e)
{
Console.WriteLine("Exception: {0}", e.ToString());
}
}
} |