C# 서버 오류..

moniteer의 이미지

소스코드 중간에 오류 표시된 부분에서 널값예외 오류가 뜹니다.
도저히 해결방법을 모르겠습니다.
알려주시면 감사하겠습니다.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
 
namespace LoginServerWF
{
    public partial class frmLoginServer : Form
    {
        public List<ClientSocket> _clientSockets { get; set; }
 
        private byte[] _buffer = new byte[1024];
        private Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 
        public frmLoginServer()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
 
            if(!Directory.Exists("log"))
            {
                Directory.CreateDirectory("log");
                _clientSockets = new List<ClientSocket>();
            }
        }
 
        private void frmLoginServer_Load(object sender, EventArgs e)
        {
            SetupServer();
        }
 
        private void SetupServer()
        {
            lStatus.Text = "Setting Up Server......";
            tbLog.AppendText("Setting Up Server......\n");
            _serverSocket.Bind(new IPEndPoint(IPAddress.Any, 32211));
            _serverSocket.Listen(1);
            lStatus.Text = "Server is Running......";
            tbLog.AppendText("Server is Running......\n");
            lStatus.BackColor = Color.Green;
            tLog.Enabled = true;
            _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
        }
 
        private void AcceptCallback(IAsyncResult ar)
        {
            Socket s = _serverSocket.EndAccept(ar);
            ClientSocket s1 = new ClientSocket(s);
            _clientSockets.Add(s1); // 오류
            lbClients.Items.Add(s.RemoteEndPoint.ToString());
            lClientsConnected.Text = "Clients connected : " + _clientSockets.Count.ToString();
            tbLog.AppendText("New Client Connected From" + s.RemoteEndPoint.ToString());
            s.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), s);
            _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
        }
 
        private void ReceiveCallback(IAsyncResult ar)
        {
            Socket s = (Socket)ar.AsyncState;
 
            if(s.Connected)
            {
                int receivedBytes;
 
                try
                {
                    receivedBytes = s.EndReceive(ar);
                }
                catch(Exception)
                {
                    for(int i = 0; i < _clientSockets.Count; i++)
                    {
                        if(_clientSockets[i]._socket.RemoteEndPoint.ToString().Equals(s.RemoteEndPoint.ToString()))
                        {
                            lbClients.Items.RemoveAt(lbClients.Items.IndexOf(s.RemoteEndPoint.ToString()));
                            _clientSockets.RemoveAt(i);
                            lClientsConnected.Text = "Clients Connected : " + _clientSockets.Count.ToString();
                        }
                    }
                    return;
                }
 
                if(receivedBytes != 0)
                {
                    byte[] dataBuffer = new byte[receivedBytes];
                    Array.Copy(_buffer, dataBuffer, receivedBytes);
                    string textReceived = Encoding.ASCII.GetString(dataBuffer);
                    HandlePacket(s, textReceived);
                }
                else
                {
                    for (int i = 0; i < _clientSockets.Count; i++)
                    {
                        if (_clientSockets[i]._socket.RemoteEndPoint.ToString().Equals(s.RemoteEndPoint.ToString()))
                        {
                            lbClients.Items.RemoveAt(lbClients.Items.IndexOf(s.RemoteEndPoint.ToString()));
                            _clientSockets.RemoveAt(i);
                            lClientsConnected.Text = "Clients Connected : " + _clientSockets.Count.ToString();
                        }
                    }
                }
            }
 
            s.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), s);
        }
 
        private void SendData(Socket s, string msgToSend)
        {
            byte[] data = Encoding.ASCII.GetBytes(msgToSend);
            s.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), s);
            _serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
        }
 
        private void SendCallback(IAsyncResult ar)
        {
            Socket s = (Socket)ar.AsyncState;
            s.EndSend(ar);
        }
 
        private void SendToSelected(string msgToSend)
        {
            for(int i = 0; i < lbClients.SelectedItems.Count; i++)
            {
                for(int j = 0; j < _clientSockets.Count; j++)
                {
                    if(lbClients.SelectedItems[i].ToString().Equals(_clientSockets[j]._socket.RemoteEndPoint.ToString()))
                    {
                        SendData(_clientSockets[j]._socket, msgToSend);
                    }
                }
            }
        }
 
        private void Broadcast(string msgToSend)
        {
            for(int i = 0; i < _clientSockets.Count; i++)
            {
                SendData(_clientSockets[i]._socket, msgToSend);
            }
        }
 
        private void Respond(Socket s, string msgToSend)
        {
            SendData(s, msgToSend);
        }
 
        private void HandlePacket(Socket s, string data)
        {
            string[] splittedData = data.Split('/');
 
            switch(splittedData[0])
            {
                default:
                    tbLog.AppendText("Unkown Packet : " + data + "\n");
                    break;
                case "0x000":
                    tbLog.AppendText("Login Request : " + splittedData[1] + " " + splittedData[2] + "\n");
                    break;
                case "0x001":
                    tbLog.AppendText("LogOut : " + splittedData[1] + " " + splittedData[2] + "\n");
                    break;
 
            }
        }
 
        private void LogToFile()
        {
            string file = ".\\log\\" + DateTime.Now.ToString("yyyy-M-d") + ".txt";
 
            if(!File.Exists(file))
            {
                File.Create(file).Dispose();
                using (TextWriter tw = new StreamWriter(file))
                {
                    tw.WriteLine("This is the Log File of the " + DateTime.Now.ToString("yyyy-M-d"));
                    tw.Close();
                }
            }
 
            File.AppendAllLines(file, tbLog.Lines);
            tbLog.Clear();
            tbLog.AppendText("Log Saved!!\n");
        }
 
        private void bSendToSelected_Click(object sender, EventArgs e)
        {
            SendToSelected(tbInput.Text);
            tbLog.AppendText("Send To Selected : " + tbInput.Text + "\n");
        }
 
        private void bBroadcast_Click(object sender, EventArgs e)
        {
            Broadcast(tbInput.Text);
            tbLog.AppendText("Send To All : " + tbInput.Text + "\n");
        }
 
        private void tLog_Tick(object sender, EventArgs e)
        {
            LogToFile();
        }
    }
 
    public class ClientSocket
    {
        public Socket _socket { get; set; }
        public string _name = "";
 
        public ClientSocket(Socket s)
        {
            this._socket = s;
        }
    }
}
chadr의 이미지

            if(!Directory.Exists("log"))
            {
                Directory.CreateDirectory("log");
                _clientSockets = new List<ClientSocket>();
            }

log라는 디렉토리가 있으면 _clientSockets를 할당 안하는데 한번 봐보세요.

-------------------------------------------------------------------------------
It's better to appear stupid and ask question than to be silent and remain stupid.

moniteer의 이미지

디렉토리에 log폴더 생성된거 삭제하니 작동이되네요..
감사합니다.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.