2015. 3. 12. 10:20
C# with TCP/IP
프로그램 설명
TcpListener와 TcpClient를 이용한 1:1 통신을 하는 프로그램입니다.
서버와 클라이언트 통신하는 순서와 아래와 같습니다.
실행 후
메시진 전송 후
프로그램 작성 순서
1. 서버 프로그램
public partial class MainForm : Form { TcpListener serverSocket = null; TcpClient clientSocket = null; public MainForm() { InitializeComponent(); // socket start new Thread(delegate() { InitSocket(); }).Start(); } private void InitSocket() { try { serverSocket = new TcpListener(IPAddress.Any, 9999); clientSocket = default(TcpClient); serverSocket.Start(); DisplayText(" >> Server Started"); clientSocket = serverSocket.AcceptTcpClient(); DisplayText(" >> Accept connection from client"); Thread threadHandler = new Thread(new ParameterizedThreadStart(OnAccepted)); threadHandler.IsBackground = true; threadHandler.Start(clientSocket); } catch (SocketException se) { DisplayText(string.Format("InitSocket : SocketException : {0}", se.Message)); } catch (Exception ex) { DisplayText(string.Format("InitSocket : Exception : {0}", ex.Message)); } } private void OnAccepted(object sender) { TcpClient clientSocket = sender as TcpClient; while (true) { try { NetworkStream stream = clientSocket.GetStream(); byte[] buffer = new byte[1024]; stream.Read(buffer, 0, buffer.Length); string msg = Encoding.Unicode.GetString(buffer); msg = msg.Substring(0, msg.IndexOf("$")); DisplayText(" >> Data from client - " + msg); string response = "Last Message from client - " + msg; byte[] sbuffer = Encoding.Unicode.GetBytes(response); stream.Write(sbuffer, 0, sbuffer.Length); stream.Flush(); DisplayText(" >> " + response); } catch (SocketException se) { DisplayText(string.Format("OnAccepted : SocketException : {0}", se.Message)); break; } catch (Exception ex) { DisplayText(string.Format("OnAccepted : Exception : {0}", ex.Message)); break; } } clientSocket.Close(); } private void DisplayText(string text) { if (richTextBoxMsg.InvokeRequired) { richTextBoxMsg.BeginInvoke(new MethodInvoker(delegate { richTextBoxMsg.AppendText(text + Environment.NewLine); })); } else richTextBoxMsg.AppendText(text + Environment.NewLine); } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { if (clientSocket != null) { clientSocket.Close(); clientSocket = null; } if (serverSocket != null) { serverSocket.Stop(); serverSocket = null; } } }
2. 클라이언트 프로그램
public partial class MainForm : Form { TcpClient clientSocket = new TcpClient(); public MainForm() { InitializeComponent(); new Thread(delegate() { InitSocket(); }).Start(); } private void InitSocket() { try { clientSocket.Connect("192.168.0.12", 9999); DisplayText("Client Started"); labelStatus.Text = "Client Socket Program - Server Connected ..."; } catch (SocketException se) { MessageBox.Show(se.Message, "Error"); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error"); } } private void btnSend_Click(object sender, EventArgs e) { NetworkStream stream = clientSocket.GetStream(); byte[] sbuffer = Encoding.Unicode.GetBytes(richTextBox2.Text + "$"); stream.Write(sbuffer, 0, sbuffer.Length); stream.Flush(); byte[] rbuffer = new byte[1024]; stream.Read(rbuffer, 0, rbuffer.Length); string msg = Encoding.Unicode.GetString(rbuffer); DisplayText(msg); richTextBox2.Text = ""; richTextBox2.Focus(); } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { if (clientSocket != null) clientSocket.Close(); } private void DisplayText(string text) { if (richTextBox1.InvokeRequired) { richTextBox1.BeginInvoke(new MethodInvoker(delegate { richTextBox1.AppendText(Environment.NewLine + " >> " + text); })); } else richTextBox1.AppendText(Environment.NewLine + " >> " + text); } }
'C# with TCP/IP' 카테고리의 다른 글
[Program C#] 서버-클라이언트 1:N 통신 (1) | 2015.03.14 |
---|---|
[Program C#] Socket multiple port로 작업하기 (0) | 2015.03.12 |
[Program C#] 비동기 접속 - 윈도우폼 (0) | 2015.03.06 |
[Program C#] 라이브러리를 이용한 클라이언트-서버 소켓 (0) | 2015.02.25 |
[Program C#]Client-Server Broadcast 예제 - 콘솔버전 (0) | 2015.02.09 |