본문 바로가기

C#

C# 개발 - TCP 네트워크 에코 시스템 모듈 프로그래밍

반응형

서버

클라이언트

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpListener tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1") ,13);
            tcpListener.Start();
            Console.WriteLine("서버");
          
            TcpClient tcpClient = tcpListener.AcceptTcpClient();
            NetworkStream networkStream = tcpClient.GetStream();
            byte[] Buffer = new byte[1024];
            int totalbyte = 0, readbyte = 0;

            while (true)
            {
                readbyte = networkStream.Read(Buffer, 0, Buffer.Length);
                if (readbyte ==0) 
                {
                    break;
                }
                totalbyte += readbyte;
                networkStream.Write(Buffer, 0, readbyte);
                Console.WriteLine(Encoding.ASCII.GetString(Buffer));

            }
            networkStream.Close();
            tcpClient.Close();
            tcpListener.Stop();

        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace ConsoleApp8
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpClient tcpClient = new TcpClient("127.0.0.1", 13);
            NetworkStream networkStream = tcpClient.GetStream();
            Console.WriteLine("클라이언트");
            byte[] Buffer = new byte[1024];
            //send
            string sendmessage = "Hellow world";
            byte[] sendbytemessage = Encoding.ASCII.GetBytes(sendmessage);
            networkStream.Write(sendbytemessage, 0, sendbytemessage.Length);
            //receive
            
            int totalcount = 0, readcount = 0;
            
            while (totalcount< sendbytemessage.Length)
            {
                
                readcount= networkStream.Read(Buffer, 0, Buffer.Length);
                totalcount += readcount;
                string receivemessage = Encoding.ASCII.GetString(Buffer);
                Console.WriteLine(receivemessage);
                
            }
            Console.WriteLine($"받은 문자열 수 : {totalcount}");
            networkStream.Close();
            tcpClient.Close();

        }
    }
}

 

반응형