Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Net;
- using System.Net.Sockets;
- using System.IO;
- namespace ChatTCP
- {
- internal class Client
- {
- public string message;
- public string text;
- public string name;
- public string sendMessage;
- static TcpClient client = new TcpClient();
- static Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- static Stream stream = null;
- static public string address = "127.0.0.1";
- static public short port = 2000;
- static IPEndPoint ep = new IPEndPoint(IPAddress.Parse(address), port);
- public bool Connect()
- {
- try
- {
- client.Connect(ep);
- socket.Connect(ep);
- if(client.Connected && socket.Connected)
- {
- stream = new NetworkStream(socket);
- message = "Подключение выполнено";
- return true;
- ProcessMessage();
- }
- else
- {
- return false;
- }
- }
- catch(Exception e)
- {
- message = $"Не удалось подключится к серверу: {e}";
- return false;
- }
- }
- public void SendMessage()
- {
- StreamWriter sw = new StreamWriter(stream);
- try
- {
- sw.WriteLine("\n" + name + ": " + text);
- }
- catch(Exception e)
- {
- message = e.ToString();
- }
- }
- private void ProcessMessage()
- {
- StreamReader sr = new StreamReader(stream);
- while (client.Connected)
- {
- try
- {
- sendMessage = sr.ReadLine();
- }
- catch (Exception e)
- {
- message = e.ToString();
- }
- System.Threading.Thread.Sleep(500);
- }
- }
- public void Disconnect()
- {
- try
- {
- client.Close();
- }
- catch(Exception e)
- {
- message = e.ToString();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement