본문 바로가기

Programming/Server

서버 간단한 tcp 통신

server

포트는 알아서 정해주자

while 문안에서 ns.Read 는 클라이언트에서 데이타를 보내줄때까지 대기한다.

클라이언트에서 데이타가 오면 온 데이타를 출력후 다시 대기

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using static System.Console;

namespace Server
{
    class Program
    {
        static int port = 7000;
        static void Main(string[] args)
        {
            WriteLine("Starting Server");
            TcpListener server = new TcpListener(IPAddress.Any, port);
            server.Start();

            WriteLine("Waiting Client");
            TcpClient client = server.AcceptTcpClient();
            WriteLine("Accept Client " + client.Client.RemoteEndPoint.ToString());

            NetworkStream ns = client.GetStream();
            while(true)            
            {
                byte [] b_Data = new byte[1024];
                ns.Read(b_Data, 0, b_Data.Length);
                Array.ForEach<byte>(b_Data, new Action<byte>(PrintValue));
                
                string s_Data = Encoding.Default.GetString(b_Data);
                WriteLine(s_Data);
            }
        }

        static void PrintValue(byte value)
        {
            if(value>0)
                Write("{0} ",value);
        }
   }
}

client

127.0.0.1 은 내 컴퓨터다. 포트는 서버에서 입력한 포트를 그대로 입력

ReadLine() 으로 보낼 메세지를 입력 받는다.

client.GetStream().Write 로 메세지를 서버에 보낸다.

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using static System.Console;

namespace client
{
    class Program
    {
        static int port = 7000;
        static string address = "127.0.0.1";
        static void Main(string[] args)
        {
            WriteLine("Starting Client");
            TcpClient client = new TcpClient();

            WriteLine("Connecting Server " + address + ":" + port);
            client.Connect(address, port);

            byte [] buf = Encoding.Default.GetBytes("Let me in!!");
            client.GetStream().Write(buf, 0, buf.Length);
            //Array.ForEach<byte>(buf, new Action<byte>(PrintValue));

            while(true)
            {
                string msg = ReadLine();
                byte [] szbuf = new byte[msg.Length];
                szbuf = Encoding.Default.GetBytes(msg);
                client.GetStream().Write(szbuf, 0, szbuf.Length);                
            }

            // WriteLine("Close Client");
            // client.Close();
        }

        static void PrintValue(byte value)
        {
            Write("{0} ",value);
        }
    }
}