클라이언트에서 메시지를 보내고 서버에서 메시지를 기록 후 클라이언트로 다시 보내주는 예제 (Winform)
참고로 쓰레드를 사용하지 않은 간단한 예제이므로 서버쪽은 멈춰있다.
쓰레드를 사용하는 예제는 다음에..
Server
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.AxHost;
namespace TcpServerSample
{
public partial class Form1 : Form
{
TcpListener m_tcpListener;
int m_port = 8686;
bool m_isRunning = false;
string chatLog = "";
public Form1()
{
InitializeComponent();
}
private void StartListener()
{
if (!m_isRunning)
{
m_isRunning = true;
richTextBox1.Text += "Start server comunication.";
// 리스너 실행
m_tcpListener = new TcpListener(IPAddress.Any, m_port);
m_tcpListener.Start();
byte[] buffer = new byte[1024];
while (true)
{
// 리스너를 통해 받은 요청에서 Stream을 가져온다.
TcpClient tcpClient = m_tcpListener.AcceptTcpClient();
NetworkStream stream = tcpClient.GetStream();
// 클라이언트가 연결을 끊을 때 까지 데이터를 수신한다.
int nbytes;
while ((nbytes = stream.Read(buffer, 0, buffer.Length)) > 0)
{
chatLog += Encoding.UTF8.GetString(buffer, 0, nbytes) + "\r\n";
richTextBox1.Text = chatLog;
richTextBox1.Update();
byte[] buf = Encoding.UTF8.GetBytes(chatLog);
stream.Write(buf, 0, buf.Length);
}
stream.Close();
tcpClient.Close();
}
}
}
private void btnStart_Click(object sender, EventArgs e)
{
StartListener();
}
}
}
Client
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TcpClientSample
{
public partial class Form1 : Form
{
TcpClient m_tcpClient;
string m_address = "127.0.0.1"; // localhost
int m_port = 8686;
int m_bufferSize = 1024;
public Form1()
{
InitializeComponent();
InitClient();
}
private void InitClient()
{
m_tcpClient = new TcpClient(m_address, m_port);
}
private bool ConnectServer()
{
return true;
}
private void SendMessage()
{
string msg = txtMessageBox.Text;
if (string.IsNullOrEmpty(msg))
{
MessageBox.Show("메시지를 입력하세요.");
return;
}
if (SendMessageToServer(message: msg, output: out string output))
{
txtMessageBox.Text = "";
txtChatBox.Text = output;
}
else
{
MessageBox.Show("메시지 전송에 실패하였습니다.");
}
}
private bool SendMessageToServer(string message, out string output)
{
try
{
// 메시지 인코딩
byte[] buffer = Encoding.UTF8.GetBytes(message);
// NetworkStream을 가져온다.
if (m_tcpClient.Client == null || !m_tcpClient.Connected)
{
m_tcpClient = new TcpClient(m_address, m_port);
}
NetworkStream stream = m_tcpClient.GetStream();
// 스트림에 데이터 전송
stream.Write(buffer, 0, buffer.Length);
// 스트림으로부터 데이터 읽기
byte[] outBuffer = new byte[m_bufferSize];
int nbytes = stream.Read(outBuffer, 0, outBuffer.Length);
output = Encoding.UTF8.GetString(outBuffer, 0, nbytes);
// 서버에서 Client를 닫을 때 까지 계속 읽는방법
//MemoryStream memoryStream = new MemoryStream();
//while ((nbytes = stream.Read(outBuffer, 0, outBuffer.Length)) > 0)
//{
// memoryStream.Write(outBuffer, 0, nbytes);
//}
//byte[] outBytes = memoryStream.ToArray();
//memoryStream.Close();
//output = Encoding.UTF8.GetString(outBytes);
// 종료
stream.Close();
m_tcpClient.Close();
return true;
}
catch (Exception ex)
{
Debug.Write(ex.Message);
output = "";
return false;
}
finally
{
m_tcpClient.Close();
}
}
private bool ReceiveMessage()
{
return true;
}
private void btnSend_Click(object sender, EventArgs e)
{
SendMessage();
}
}
}
클라이언트에서 메시지 입력후 Send 를 누르면 서버에서 받아서 메시지 로그를 남기고 다시 리턴해준다.
참조 블로그
https://www.csharpstudy.com/net/article/5-TCP-%EC%84%9C%EB%B2%84
TCP 서버 - C# 프로그래밍 배우기 (Learn C# Programming)
TCP 서버 TcpListener 클래스 .NET Framework에서 TCP 서버 프로그램을 개발하기 위해서는 System.Net.Sockets.TcpListener 클래스를 사용한다. TcpListener 클래스는 내부적으로 System.Net.Sockets.Socket 클래스 기능들을
www.csharpstudy.com
https://www.csharpstudy.com/net/article/4-TCP-%ED%81%B4%EB%9D%BC%EC%9D%B4%EC%96%B8%ED%8A%B8
TCP 클라이언트 - C# 프로그래밍 배우기 (Learn C# Programming)
TCP 클라이언트 TcpClient 클래스 .NET Framework에서 TCP 클라이언트 프로그램을 개발하기 위해서는 System.Net.Sockets.TcpClient 클래스를 사용할 수 있다. TcpClient 클래스는 내부적으로 System.Net.Sockets.Socket 클
www.csharpstudy.com
'C# .Net' 카테고리의 다른 글
RESTful API Server 구현 예제 in C# (0) | 2022.09.19 |
---|---|
A, B, C, D, ... Z, AA, AB, AC, ... AZ, BA, BB, ... ZZ, AAA, AAB... 등 알파벳 이름 자동 생성 in C# (Excel 방식) 예제 (0) | 2022.09.14 |
Json / Xml to DataSet (0) | 2022.02.25 |
.Net C/C++/C# Stack Size 변경 방법 (0) | 2021.11.17 |