using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows;
using Firebase.Database;
using Firebase.Database.Query;
namespace ChatClient
{
public partial class MainWindow : Window
{
TcpClient clientSocket = new TcpClient();
NetworkStream stream = default(NetworkStream);
string message = string.Empty;
StreamWriter writer;
StreamReader reader;
FirebaseClient firebaseClient;
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ConnectToServer();
ConnectToFirebase();
}
private void ConnectToServer()
{
try
{
clientSocket.Connect("127.0.0.1", 7777);
stream = clientSocket.GetStream();
writer = new StreamWriter(stream, Encoding.UTF8) { AutoFlush = true };
reader = new StreamReader(stream, Encoding.UTF8);
Thread receiveThread = new Thread(ReceiveMessages);
receiveThread.IsBackground = true;
receiveThread.Start();
writer.WriteLine("User" + new Random().Next(1000)); // 임의의 사용자 이름 전송
}
catch (Exception ex)
{
MessageBox.Show("서버 연결 실패: " + ex.Message);
}
}
private void ConnectToFirebase()
{
firebaseClient = new FirebaseClient("https://your-database-name.firebaseio.com/");
var observable = firebaseClient
.Child("messages")
.AsObservable<Message>()
.Subscribe(d => this.Dispatcher.Invoke(() =>
{
chatList.Items.Add(d.Object.Message);
}));
}
private void ReceiveMessages()
{
while (true)
{
try
{
message = reader.ReadLine();
if (message != null)
{
this.Dispatcher.Invoke(() =>
{
chatList.Items.Add(message);
});
}
}
catch (Exception ex)
{
this.Dispatcher.Invoke(() =>
{
chatList.Items.Add("서버 연결 끊김: " + ex.Message);
});
break;
}
}
}
private void sendButton_Click(object sender, RoutedEventArgs e)
{
if (!string.IsNullOrWhiteSpace(messageBox.Text))
{
writer.WriteLine(messageBox.Text);
messageBox.Clear();
}
}
public class Message
{
public string Message { get; set; }
}
}
}
--클라이언트 XAML--
<Window x:Class="ChatClient.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Chat Client" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<ListBox x:Name="chatList" HorizontalAlignment="Left" Height="238" Margin="10,10,0,0" VerticalAlignment="Top" Width="497"/>
<TextBox x:Name="messageBox" HorizontalAlignment="Left" Height="23" Margin="10,258,0,0" VerticalAlignment="Top" Width="414"/>
<Button Content="Send" HorizontalAlignment="Left" Margin="429,258,0,0" VerticalAlignment="Top" Width="78" Click="sendButton_Click"/>
</Grid>
</Window>