using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace EchoServer
{
class EchoServer
{
private TcpListener Server;
private Int32 port = 13000;
static void Main(string[] args)
{
EchoServer server = new EchoServer();
if (args.Length > 0)
{
server.port = Int32.Parse(args[0]);
}
server.ServerStart();
}
public void ServerStart()
{
try
{
Byte[] bytes = new Byte[256];
String data = null;
int i;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
Server = new TcpListener(localAddr, port);
Server.Start();
Console.WriteLine("EchoServer Start : ip : " + localAddr.ToString() + " Port : " + port.ToString());
while (true)
{
Console.Write("Waiting for a connection...");
TcpClient client = Server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
NetworkStream stream = client.GetStream();
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine(String.Format("Recieved: {0}", data));
Byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
Console.WriteLine(String.Format("Sent: {0}", data));
}
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
catch (Exception e)
{
Console.WriteLine("Exception : Not Connected");
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}
}
Echo Client
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;namespace EchoServer
{
class EchoClient
{
IPAddress SvrIP = IPAddress.Parse("127.0.0.1");
Int32 port = 13000;public static void Main(string[] args)
{
EchoClient echoClient = new EchoClient();
echoClient.client();
}private void client()
{
try
{
TcpClient client = new TcpClient("127.0.0.1", port);Console.WriteLine("서버 연결 ... [" + SvrIP.ToString() + "]");
string msg = null;
Byte[] data = new Byte[256];NetworkStream stream = client.GetStream();
while (true)
{
Console.Write("me : ");
msg = Console.ReadLine();
data = System.Text.Encoding.ASCII.GetBytes(msg);
stream.Write(data, 0, data.Length);
//Console.WriteLine(String.Format("Sent: {0}", msg));stream.Read(data, 0, data.Length);
msg = System.Text.Encoding.ASCII.GetString(data);
Console.WriteLine(String.Format("Receive : {0}", msg));
}stream.Close();
client.Close();}
catch (SocketException se)
{
Console.WriteLine(se.Message);
}
catch (Exception e)
{
Console.WriteLine("Exception");
Console.ReadLine();
}
}
}
}
'개발 > C# .NET' 카테고리의 다른 글
web query분석기 (0) | 2008.08.27 |
---|---|
C#에서 네트웍정보 조회하기 (0) | 2008.08.27 |
C#에서 Oracle 연결하기 (0) | 2008.05.16 |