U E D R , A S I H C RSS

조영준/다대다채팅 (rev. 1.1)

조영준/다대다채팅

조영준의 하위문서입니다.

개요

  • 새싹교실에서 소켓에 대해 배우고 쓰레드에 대해 배운 다음에 삘받아서 슉슉 만든 프로그램.
  • 원래 있던 일대일 채팅 프로그램을 개조.
  • 날림 제작이라 코드가 더러...운지 아닌지도 모름. 다시 본 적이 없어서 :Q... 개판인건 확실할듯.
  • 솔직히 어떻게 짰는지 기억도 안난다. 말 그대로 '으어어어어' 하다보니 작동이 됨.
  • 사실 구조까지 혼자 해 보려다가 멘붕하고 인터넷에서 구조는 찾아봄...

코드

서버

Program.cs

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

using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace CSharpSocketServer
{
    class Program
    {
        static void Main(string[] args)
        {
            ChatServer server = new ChatServer();
            server.Do();
        }
    }
}

ChatServer.cs

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

using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace CSharpSocketServer
{
    class ChatServer
    {
        private TcpListener serverSocket;
        static private List<ChatClient> ClientList;
        public ChatServer()
        {
            serverSocket = new TcpListener(5555);
            ClientList = new List<ChatClient>();
        }
        public void Do()
        {
            Thread t1 = new Thread(new ThreadStart(manageConnection));
            Thread t3 = new Thread(new ThreadStart(ManageChat));

            serverSocket.Start();
            Console.WriteLine(TimeStamp() + "[]Server started");

            t1.Start();
            t3.Start();

            t1.Join();
            t3.Join();

            serverSocket.Stop();

            Console.WriteLine(TimeStamp() + "[]End");
            Console.ReadLine();
        }
        static public void broadcast(string s)
        {
            Queue<int> toRemove = new Queue<int>();

            int count = 0;
            foreach (ChatClient cc in ClientList)
            {
                count++;
                try
                {
                    string dataSend = s;
                    NetworkStream stream = cc.socket.GetStream();
                    byte[] byteSend = Encoding.ASCII.GetBytes(dataSend);
                    stream.Write(byteSend, 0, byteSend.Length);
                    byteSend = null;
                }
                catch(Exception e)
                {
                    toRemove.Enqueue(count);
                    Console.WriteLine(TimeStamp() + "!! " + e.Message);
                }
            }
            count = 0;
            while (!(toRemove.Count == 0))
            {
                count++;
                ClientList.RemoveAt(toRemove.Dequeue()-count);
            }
            Console.WriteLine(TimeStamp() + s);
        }
        private void manageConnection()
        {
            while (true)
            {
                ChatClient tempClient = new ChatClient(serverSocket.AcceptTcpClient());
                ClientList.Add(tempClient);
                tempClient.start();
                
            }
        }
        private void ManageChat()
        {
            while (true)
            {
                string s = Console.ReadLine();
                if (s == "exit") break;
                broadcast("SERVER : " + s);
            }

        }
        static public string TimeStamp()
        {
            return DateTime.Now.ToShortTimeString() + ":" + DateTime.Now.Second + "." + DateTime.Now.Millisecond + " ";
        }

    }
}

ChatClient.cs

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

using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace CSharpSocketServer
{
    class ChatClient
    {
        public string name;
        public TcpClient socket;
        private NetworkStream stream;
        private byte[] byteGet;

        public ChatClient(TcpClient c)
        {
            Console.WriteLine(ChatServer.TimeStamp() + "[]Connection established");
            socket = c;
            socket.ReceiveBufferSize = 1024;
            
        }
        public void start()
        {
            stream = socket.GetStream();
            byteGet = new byte[1024];
            Thread t = new Thread(new ThreadStart(doChat));
            t.Start();
            /*
            t.Join();
            
            socket.Close();
            stream.Close();
            */

            
        }
        private void doChat()
        {
            string dataGet;
            try
            {
                byteGet = new byte[1024];
                stream.Read(byteGet, 0, socket.ReceiveBufferSize);
                dataGet = Encoding.ASCII.GetString(byteGet).TrimEnd('\0');
                name = dataGet;
                ChatServer.broadcast(name + " joined");
                
            }
            catch(Exception e)
            {
                Console.WriteLine(ChatServer.TimeStamp() + "!! " + e.Message);
                return;
            }
            while (true)
            {
                try
                {
                    byteGet = new byte[1024];
                    stream.Read(byteGet, 0, socket.ReceiveBufferSize);
                    dataGet = Encoding.ASCII.GetString(byteGet).TrimEnd('\0');
                    ChatServer.broadcast(name + " : " + dataGet);
                }
                catch (Exception e)
                {
                    Console.WriteLine(ChatServer.TimeStamp() + "!! " + e.Message);
                    break;
                }
            }
        }
    }
}


클라이언트

Program.cs

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

using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace CSharpSocketClient
{
    class Program
    {
        static private TcpClient clientSocket;
        static private NetworkStream networkStream;
        static void Main(string[] args)
        {
            Thread t1 = new Thread(new ThreadStart(read));
            Thread t2 = new Thread(new ThreadStart(write));
            try
            {
                clientSocket = new TcpClient();
                clientSocket.ReceiveBufferSize = 1024;
                clientSocket.SendBufferSize = 1024;
                clientSocket.Connect("127.0.0.1", 5555);
                Console.WriteLine(TimeStamp() + "[] Connection established");

                networkStream = clientSocket.GetStream();

                t1.Start();
                t2.Start();                
            }
            catch (Exception e)
            {
                Console.WriteLine(TimeStamp() + "!! " + e.Message);
            }

            
            t1.Join();
            t2.Join();
            networkStream.Close();
            clientSocket.Close();
            Console.WriteLine(TimeStamp() + "[] End");
            Console.ReadLine();
        }

        static void read()
        {
            byte[] byteGet = new byte[1024];
            string dataGet;
            while (true)
            {
                try
                {
                    byteGet = new byte[1024];
                    networkStream.Read(byteGet, 0, clientSocket.ReceiveBufferSize);
                    dataGet = Encoding.ASCII.GetString(byteGet).TrimEnd('\0');
                    Console.WriteLine(TimeStamp() + dataGet);
                }
                catch(Exception e)
                {
                    Console.WriteLine(TimeStamp() + "!! " + e.Message);
                    return;
                }
            }
        }
        static void write()
        {
            string s;
            byte[] byteSend = new byte[1026];
            while (true)
            {
                s = Console.ReadLine();
                byteSend=Encoding.ASCII.GetBytes(s);
                networkStream.Write(byteSend, 0, byteSend.Length);
            }
        }

        static string TimeStamp()
        {
            return DateTime.Now.ToShortTimeString() + ":" + DateTime.Now.Second + "." + DateTime.Now.Millisecond + " ";
        }
    }
}

Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:31:07
Processing time 0.0983 sec