소켓 프로그래밍에서 간단한 응용 프로그램을 만듭니다. 나는 이것이 이것을 달성하는 간단한 방법이라고 생각한다. 그래서 이것이 내가 이것을 나눠주고있는 이유입니다. 이 프로그램에서는 서버 프로그램 및 클라이언트 프로그램을 만들 수 있습니다. 또한 클라이언트와 서버에서 메시지를주고받을 수 있습니다. 여기 내 코드간단한 프로그래밍 예제 C가 날카로운
서버 프로그램입니다 : -
class Program
{
private const int port = 4532;
static void Main(string[] args)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 4532);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ip);
socket.Listen(10);
Console.WriteLine("Waiting for client");
Socket client = socket.Accept();
IPEndPoint clientIP = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine(" >> Connected with" + clientIP.Address + "at port" + clientIP.Port);
Console.WriteLine(" >> Accept connection from client");
string welcome = "Welcome";
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(welcome);
client.Send(data, data.Length, SocketFlags.None);
Console.WriteLine("......");
Console.Read();
}
}
클라이언트 프로그램 : -
class Program
{
static void Main(string[] args)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4532);
Console.WriteLine("Client Started");
try
{
socket.Connect(ip);
}
catch(SocketException e)
{
Console.WriteLine("Enable to connect");
}
Console.WriteLine("Conneted to server");
byte[] data = new byte[1024];
int receivedata = socket.Receive(data);
string stringdata = Encoding.ASCII.GetString(data, 0, receivedata);
Console.WriteLine(stringdata);
Console.Read();
}
}