Toggle menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

조영준/다대다채팅: Difference between revisions

From ZeroWiki
imported>skywave
No edit summary
 
(Repair batch-0007 pages from live compare)
 
Line 24: Line 24:
     class Program
     class Program
     {
     {
         static void Main(string[] args)
         static void Main(string[] args)
         {
         {
             ChatServer server = new ChatServer();
             ChatServer server = new ChatServer();
Line 59: Line 59:
   
   
             serverSocket.Start();
             serverSocket.Start();
             Console.WriteLine(TimeStamp() + "[]Server started");
             Console.WriteLine(TimeStamp() + "[]Server started");
   
   
             t1.Start();
             t1.Start();
Line 69: Line 69:
             serverSocket.Stop();
             serverSocket.Stop();
   
   
             Console.WriteLine(TimeStamp() + "[]End");
             Console.WriteLine(TimeStamp() + "[]End");
             Console.ReadLine();
             Console.ReadLine();
         }
         }
Line 84: Line 84:
                     string dataSend = s;
                     string dataSend = s;
                     NetworkStream stream = cc.socket.GetStream();
                     NetworkStream stream = cc.socket.GetStream();
                     byte[] byteSend = Encoding.ASCII.GetBytes(dataSend);
                     byte[] byteSend = Encoding.ASCII.GetBytes(dataSend);
                     stream.Write(byteSend, 0, byteSend.Length);
                     stream.Write(byteSend, 0, byteSend.Length);
                     byteSend = null;
                     byteSend = null;
Line 147: Line 147:
         public TcpClient socket;
         public TcpClient socket;
         private NetworkStream stream;
         private NetworkStream stream;
         private byte[] byteGet;
         private byte[] byteGet;
   
   
         public ChatClient(TcpClient c)
         public ChatClient(TcpClient c)
         {
         {
             Console.WriteLine(ChatServer.TimeStamp() + "[]Connection established");
             Console.WriteLine(ChatServer.TimeStamp() + "[]Connection established");
             socket = c;
             socket = c;
             socket.ReceiveBufferSize = 1024;
             socket.ReceiveBufferSize = 1024;
Line 159: Line 159:
         {
         {
             stream = socket.GetStream();
             stream = socket.GetStream();
             byteGet = new byte[1024];
             byteGet = new byte[1024];
             Thread t = new Thread(new ThreadStart(doChat));
             Thread t = new Thread(new ThreadStart(doChat));
             t.Start();
             t.Start();
Line 176: Line 176:
             try
             try
             {
             {
                 byteGet = new byte[1024];
                 byteGet = new byte[1024];
                 stream.Read(byteGet, 0, socket.ReceiveBufferSize);
                 stream.Read(byteGet, 0, socket.ReceiveBufferSize);
                 dataGet = Encoding.ASCII.GetString(byteGet).TrimEnd('\0');
                 dataGet = Encoding.ASCII.GetString(byteGet).TrimEnd('\0');
Line 192: Line 192:
                 try
                 try
                 {
                 {
                     byteGet = new byte[1024];
                     byteGet = new byte[1024];
                     stream.Read(byteGet, 0, socket.ReceiveBufferSize);
                     stream.Read(byteGet, 0, socket.ReceiveBufferSize);
                     dataGet = Encoding.ASCII.GetString(byteGet).TrimEnd('\0');
                     dataGet = Encoding.ASCII.GetString(byteGet).TrimEnd('\0');
Line 225: Line 225:
         static private TcpClient clientSocket;
         static private TcpClient clientSocket;
         static private NetworkStream networkStream;
         static private NetworkStream networkStream;
         static void Main(string[] args)
         static void Main(string[] args)
         {
         {
             Thread t1 = new Thread(new ThreadStart(read));
             Thread t1 = new Thread(new ThreadStart(read));
Line 235: Line 235:
                 clientSocket.SendBufferSize = 1024;
                 clientSocket.SendBufferSize = 1024;
                 clientSocket.Connect("127.0.0.1", 5555);
                 clientSocket.Connect("127.0.0.1", 5555);
                 Console.WriteLine(TimeStamp() + "[] Connection established");
                 Console.WriteLine(TimeStamp() + "[] Connection established");
   
   
                 networkStream = clientSocket.GetStream();
                 networkStream = clientSocket.GetStream();
Line 252: Line 252:
             networkStream.Close();
             networkStream.Close();
             clientSocket.Close();
             clientSocket.Close();
             Console.WriteLine(TimeStamp() + "[] End");
             Console.WriteLine(TimeStamp() + "[] End");
             Console.ReadLine();
             Console.ReadLine();
         }
         }
Line 258: Line 258:
         static void read()
         static void read()
         {
         {
             byte[] byteGet = new byte[1024];
             byte[] byteGet = new byte[1024];
             string dataGet;
             string dataGet;
             while (true)
             while (true)
Line 264: Line 264:
                 try
                 try
                 {
                 {
                     byteGet = new byte[1024];
                     byteGet = new byte[1024];
                     networkStream.Read(byteGet, 0, clientSocket.ReceiveBufferSize);
                     networkStream.Read(byteGet, 0, clientSocket.ReceiveBufferSize);
                     dataGet = Encoding.ASCII.GetString(byteGet).TrimEnd('\0');
                     dataGet = Encoding.ASCII.GetString(byteGet).TrimEnd('\0');
Line 279: Line 279:
         {
         {
             string s;
             string s;
             byte[] byteSend = new byte[1026];
             byte[] byteSend = new byte[1026];
             while (true)
             while (true)
             {
             {
Line 294: Line 294:
     }
     }
  }
  }

Latest revision as of 01:32, 27 March 2026

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

개요

  • 새싹교실에서 소켓에 대해 배우고 쓰레드에 대해 배운 다음에 삘받아서 슉슉 만든 프로그램.
  • 원래 있던 일대일 채팅 프로그램을 개조.
  • 날림 제작이라 코드가 더러...운지 아닌지도 모름. 다시 본 적이 없어서 :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 + " ";
        }
    }
}