C# 서버 오류..
글쓴이: moniteer / 작성시간: 일, 2017/06/04 - 11:06오전
소스코드 중간에 오류 표시된 부분에서 널값예외 오류가 뜹니다.
도저히 해결방법을 모르겠습니다.
알려주시면 감사하겠습니다.
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; } } }
Forums:
if(!Directory.Exists("log"))
log라는 디렉토리가 있으면 _clientSockets를 할당 안하는데 한번 봐보세요.
-------------------------------------------------------------------------------
It's better to appear stupid and ask question than to be silent and remain stupid.
감사합니다.
디렉토리에 log폴더 생성된거 삭제하니 작동이되네요..
감사합니다.
댓글 달기