C#

(C#) 네트워크 프로그램, 1:1 채팅 프로그램

코딩ABC 2023. 4. 23. 07:08
반응형

TcpListener 클래스를 이용해서 서버 기능을 구현합니다.

TcpClient 클래스를 이용해서 클라이언트 기능을 구현합니다.

 

아래의 코드는 1:1 채팅이 가능한 윈폼(Windows Forms 앱(.NET Framework)) 프로그램의 코드입니다.

 

채팅11 서버

 

채팅11 클라이언트

 

 

서버 프로그램

using System;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;

namespace 채팅11_서버
{
    public partial class Form1 : Form
    {
        TcpListener server;
        TcpClient client;
        StreamReader reader;
        StreamWriter writer;
        NetworkStream stream;
        Thread receiveThread;
        bool connected;
        private delegate void AddTextDelegate(string s);

        public Form1()
        {
            InitializeComponent();
            this.Text = "채팅서버 - 0012000 정경환";
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Thread listenThread = new Thread(new ThreadStart(Listen));
            listenThread.Start();
        }
        private void Listen()
        {
            AddTextDelegate AddText = new AddTextDelegate(txtMessage.AppendText);
            try
            {
                IPAddress addr = new IPAddress(0);
                int port = 15000;
                server = new TcpListener(addr, port);
                server.Start();
                Invoke(AddText, "서버가 시작되었습니다.\r\n");

                client = server.AcceptTcpClient();
                connected = true;
                Invoke(AddText, "클라이언트가 연결되었습니다.\r\n");

                stream = client.GetStream();
                reader = new StreamReader(stream);
                writer = new StreamWriter(stream);

                receiveThread = new Thread(new ThreadStart(Receive));
                receiveThread.Start();
            }
            catch(Exception ee)
            {
            }
        }
        private void Receive()
        {
            AddTextDelegate AddText = new AddTextDelegate(txtMessage.AppendText);
            try
            {
                while(connected)
                {
                    Thread.Sleep(1);
                    if(stream.CanRead)
                    {
                        string temp = reader.ReadLine();
                        if(temp.Length > 0)
                        {
                            //Invoke(AddText, "클라이언트: " + temp + "\r\n");
                            Invoke(AddText, ">> " + temp + "\r\n");
                            toolStripStatusLabel1.Text = "메시지 받은 시간:" +
                                DateTime.Now.ToString();
                        }
                    }
                }
            }
            catch
            {
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                writer.WriteLine(txtSend.Text);
                writer.Flush();
                txtMessage.AppendText(txtSend.Text + "\r\n");
                txtSend.Clear();
            }
            catch
            {
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (reader != null) reader.Close();
            if (writer != null) writer.Close();
            if (server != null) server.Stop();
            if (client != null) client.Close();
            if (receiveThread != null) receiveThread.Abort();
        }
    }
}

 

 

반응형

 

클라이언트 프로그램

using System;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace 채팅11
{
    public partial class Form1 : Form
    {
        //TcpListener server;
        TcpClient client;
        StreamReader reader;
        StreamWriter writer;
        NetworkStream stream;
        Thread receiveThread;
        bool connected;
        private delegate void AddTextDelegate(string s);

        public Form1()
        {
            InitializeComponent();
            this.Text = "채팅11";
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        private void Receive()
        {
            AddTextDelegate AddText = new AddTextDelegate(txtMessage.AppendText);
            try
            {
                while(connected)
                {
                    Thread.Sleep(1);
                    if(stream.CanRead)
                    {
                        string temp = reader.ReadLine();
                        if(temp.Length > 0)
                        {
                            Invoke(AddText, ">> " + temp + "\r\n");
                            toolStripStatusLabel1.Text = "메시지 도착 시간:" +
                                DateTime.Now.ToString();
                        }
                    }
                }
            }
            catch
            {
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                writer.WriteLine(txtSend.Text);
                writer.Flush();
                txtMessage.AppendText(txtSend.Text + "\r\n");
                txtSend.Clear();
            }
            catch(Exception ee)
            {
                txtMessage.AppendText("메시지를 보낼 수 없습니다.\r\n");
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (reader != null) reader.Close();
            if (writer != null) writer.Close();
            if (client != null) client.Close();
            if (receiveThread != null) receiveThread.Abort();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 서버 연결
            if(txtServerIP.Text == "")
            {
                MessageBox.Show("IP를 입력하세요");
                txtServerIP.Focus();
                return;
            }
            try
            {
                string ip = txtServerIP.Text;
                int port = 15000;
                client = new TcpClient();
                client.Connect(ip, port);
                stream = client.GetStream();
                connected = true;
                txtMessage.AppendText("서버에 연결되었습니다.\r\n");
                reader = new StreamReader(stream);
                writer = new StreamWriter(stream);
                receiveThread = new Thread(new ThreadStart(Receive));
                receiveThread.Start();
            }
            catch
            {
                txtMessage.AppendText("서버에 연결할 수 없습니다.\n\r");
            }
        }
    }
}

 

반응형