blob: e9d4b54ab35a505f0296fd73e025f10878b1e827 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace Client
{
public class TcpChatClient : INotifyPropertyChanged
{
public int Port { get; set; }
private string log;
public string Log
{
get
{
return log;
}
set
{
log = value;
OnPropertyChanged();
}
}
public bool Status { get; set; }
private StreamReader sr;
private StreamWriter sw;
public TcpChatClient()
{
}
public async Task Connect(string ipAddress, int port)
{
TcpClient clientSocket = new TcpClient(ipAddress, port);
NetworkStream ns = clientSocket.GetStream();
sr = new StreamReader(ns);
sw = new StreamWriter(ns);
sw.AutoFlush = true;
Status = true;
await ReceiveMessageAsync();
}
public void SendMessage(string message)
{
sw.WriteLine(message);
}
private async Task ReceiveMessageAsync()
{
while (Status)
{
string message = await sr.ReadLineAsync();
Log += $"{message}\n";
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|