간단한 서버
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// 소켓 프로그래밍 기초
/// </summary>
namespace ServerCore
{
class Program
{
static void Main(string[] args)
{
/// DNS (Domain Name System)
/// 172.1.2.3(실제로 넣으면 문제가됨!) 하드코딩 X!
/// 하지만 도메인 등록이라면 문제가 없다
/// www.rookiss.com -> 123.123.123.12
string host = Dns.GetHostName();
IPHostEntry ipHost = Dns.GetHostEntry(host);
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint endPoint = new IPEndPoint(ipAddr, 7777);
///식당주소 -> ipAddr
///식당 정문,후문 인지 ->7777 (port)
///문지기 만들기(핸드폰만들기)
Socket listenSocket = new Socket(endPoint.AddressFamily,SocketType.Stream,ProtocolType.Tcp);
try
{
///문지기 교육시키기(문지기 핸드폰에 주소연동)
listenSocket.Bind(endPoint);
///영업 시작
///backlog : 최대 대기수
/// 문지기가 안내하기 전까지 대기하는 수
/// 만약 이 수가 넘어가는 사람이 문의하면 바로 fail이 뜬다
listenSocket.Listen(10);
while (true)
{
Console.WriteLine("Listening...");
/// 손님을 입장시킨다.
Socket clientSocket = listenSocket.Accept(); ///손님과 대화할 소켓 생성
/// 받는다
byte[] recvBuff = new byte[1024];
int recvBytes = clientSocket.Receive(recvBuff);
string recvData = Encoding.UTF8.GetString(recvBuff, 0, recvBytes);
Console.WriteLine($"From Client[{recvData}]");
/// 보낸다
byte[] sendBuff = Encoding.UTF8.GetBytes("Welcome to MMORPG SERVER!");
clientSocket.Send(sendBuff);
///쫒아낸다
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
간단한 클라이언트
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
/// <summary>
/// 유니티 대신해서 테스트 하기위한 클라이언트
/// 테스팅 환경 구축용
/// </summary>
///
namespace DummyClient
{
class Program
{
static void Main(string[] args)
{
/// DNS (Domain Name System)
/// 172.1.2.3(실제로 넣으면 문제가됨!) 하드코딩 X!
/// 하지만 도메인 등록이라면 문제가 없다
/// www.rookiss.com -> 123.123.123.12
string host = Dns.GetHostName();
IPHostEntry ipHost = Dns.GetHostEntry(host);
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint endPoint = new IPEndPoint(ipAddr, 7777);
///휴대폰 설정
Socket socket = new Socket(endPoint.AddressFamily,SocketType.Stream,ProtocolType.Tcp);
try
{
///문지기한테 입장 문의
socket.Connect(endPoint);
Console.WriteLine($"Connected To{socket.RemoteEndPoint.ToString()}");
///보낸다
byte[] sendBuff = Encoding.UTF8.GetBytes("Hello World!");
int sendBytes = socket.Send(sendBuff);
///받는다
byte[] recvBuff = new byte[1024];
int recvBytes = socket.Receive(recvBuff);
string receiveData = Encoding.UTF8.GetString(recvBuff, 0, recvBytes);
Console.WriteLine($"From server{receiveData }");
///나간다
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
///
}
}
}
댓글 없음:
댓글 쓰기