C#, 콘솔채팅동영상, Console Chat, 멀티쓰레드 클라이언트,서버, TcpClient, TcpListener, C#네트워크교육, 시샵학원, C#학원, 닷넷학원, 닷넷교육동영상
http://ojc.asia/bbs/board.php?bo_table=LecCsharpNet&wr_id=55
ojc.asia
https://www.youtube.com/watch?v=9Hkqgs4o-sc&list=PLxU-iZCqT52CA9Y474h7UbqmWqXwIZ-hl&index=2

https://www.youtube.com/watch?v=RLiaZaEdyqs&list=PLxU-iZCqT52CA9Y474h7UbqmWqXwIZ-hl&index=1


콘솔기반 채팅 프로그램
실습

콘솔기반의 채팅 프로그램
이전 강좌 멀티쓰레드기반 Echo 클라이언트/서버에 아래 기능이 추가되면 된다.
- 서버 : 클라이언트의 접속을 받는 AcceptSocket() 이후 만들어진 클라이언트 처리용 소켓을 List<Socket> 형태의 ArrayList에 보관한다. 그리도 난 후 글을 쓰는 부분에서 foreach문으로 접속해 있는 모든 클라이언트에 글을 쓸 수 있도록 해야 한다.
- 클라이언트 : 수시로 서버에서 전송되어 넘어오는 글을 콘솔화면에 쓰기 위해 글 읽는 부분을 쓰레드로 구성해야 한다.
[서버]

[클라이언트]


1. 서버
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections.Generic;
class ClientHandler
{
NetworkStream stream = null;
StreamReader reader = null;
StreamWriter writer = null;
Socket socket = null;
public ClientHandler(Socket socket)
{
this.socket = socket;
Server.list.Add(socket);
}
public void chat()
{
stream = new NetworkStream(socket);
reader = new StreamReader(stream);
try
{
while (true)
{
string str = reader.ReadLine();
Console.WriteLine(str);
// ArrayList에 보관된 모든 클라이언트 처리 소켓만큼
// 현재 접속한 모든 클라이언트에게 글을 씀
foreach (Socket s in Server.list)
{
//클라이언트의 데이터를 읽고, 쓰기 위한 스트림을 만든다.
//자신한테는 글을 되보내지 않는다.
if (s != socket)
{
stream = new NetworkStream(s);
writer = new StreamWriter(stream) { AutoFlush = true };
writer.WriteLine(str);
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
Server.list.Remove(socket);
socket.Close();
socket = null;
}
}
}
class Server
{
// 클라이언트가 다수 접속하므로 서버가 AcceptSocket 으로 생성한
// 클라이언트 상대하는 소켓을 ArrayList등에 보관하고 글을 쓸 때
// 현재 접속한 클라이언트 모두에게 글을 보내야 한다.
public static List<Socket> list = new List<Socket>();
public static void Main()
{
TcpListener tcpListener = null;
Socket clientsocket = null;
try
{
//IP주소를 나타내는 객체를 생성,TcpListener를 생성시 인자로 사용할려고
IPAddress ipAd = IPAddress.Parse("127.0.0.1");
//TcpListener Class를 이용하여 클라이언트의 연결을 받아 들인다.
tcpListener = new TcpListener(ipAd, 5001);
tcpListener.Start();
//Client의 접속이 올때 까지 Block 되는 부분, 대개 이부분을 Thread로 만들어 보내 버린다.
//백그라운드 Thread에 처리를 맡긴다.
while (true)
{
clientsocket = tcpListener.AcceptSocket();
ClientHandler cHandler = new ClientHandler(clientsocket);
Thread t = new Thread(new ThreadStart(cHandler.chat));
t.Start();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
clientsocket.Close();
}
}
}
2. 클라이언트
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
class ServerHandler
{
StreamReader reader = null;
public ServerHandler(StreamReader reader)
{
this.reader = reader;
}
//서버에서 불특정하게 날아오는 다른 Client가 쓴 내용을
//받기 위해 클라이언트의 글읽는 부분을 쓰레드로 처리
public void chat()
{
try
{
while (true)
{
Console.WriteLine(reader.ReadLine());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
class TcpClientTest
{
static void Main(string[] args)
{
TcpClient client = null;
try
{
//LocalHost에 지정 포트로 TCP Connection을 생성하고 데이터를 송수신 하기
//위한 스트림을 얻는다.
client = new TcpClient();
client.Connect("localhost", 5001);
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(stream);
StreamWriter writer = new StreamWriter(stream)
{ AutoFlush = true };
//글읽는 부분을 ServerHandler에서 처리하도록 쓰레드로 만든다.
ServerHandler serverHandler = new ServerHandler(reader);
Thread t = new Thread(new ThreadStart(serverHandler.chat));
t.Start();
string dataToSend = Console.ReadLine();
while (true)
{
writer.WriteLine(dataToSend);
if (dataToSend.IndexOf("<EOF>") > -1) break;
dataToSend = Console.ReadLine();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
client.Close();
client = null;
}
}
}
#시샵채팅, #콘솔채팅, #ConsoleChat, #시샵멀티쓰레드, #TcpClient, #TcpListener, #닷넷채팅, #닷넷교육, #시샵교육, #시샵학원, 시샵채팅, 콘솔채팅, ConsoleChat, 시샵멀티쓰레드, TcpClient, TcpListener, 닷넷채팅, 닷넷교육, 시샵교육, 시샵학원,