Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Net.Sockets;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading;
- namespace ConsoleChatClient
- {
- class Program
- {
- static string UserName;
- private static string Host;
- private static int Port;
- static TcpClient Client;
- static NetworkStream Stream;
- static void InitializeSocket()
- {
- try
- {
- Client.Connect(Host, Port);
- Stream = Client.GetStream();
- }
- catch(Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- }
- static void Disconnect()
- {
- if(Stream != null)
- {
- Stream.Close();
- }
- if(Client != null)
- {
- Client.Close();
- }
- Environment.Exit(0);
- }
- static void RecieveMessages()
- {
- while(true)
- {
- try
- {
- byte[] data = new byte[64];
- StringBuilder Builder = new StringBuilder();
- int bytes = 0;
- do
- {
- bytes = Stream.Read(data, 0, data.Length);
- Builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
- }
- while (Stream.DataAvailable);
- String message = Builder.ToString();
- Console.WriteLine(message);
- }
- catch
- {
- Console.WriteLine("Connection closed!");
- Console.ReadLine();
- Disconnect();
- }
- }
- }
- static void InitializeConnection()
- {
- Thread InputThread = new Thread(RecieveMessages);
- InputThread.Start();
- byte[] UserNameBuffer = Encoding.Unicode.GetBytes(UserName);
- try
- {
- Stream.Write(UserNameBuffer, 0, UserNameBuffer.Length);
- }
- catch
- {
- Disconnect();
- }
- }
- static void SendMessages()
- {
- String Message = "";
- while (Message.ToLower() != "@exit")
- {
- Message = Console.ReadLine().Trim();
- if(String.IsNullOrEmpty(Message))
- {
- continue;
- }
- byte[] WriteBuffer = Encoding.Unicode.GetBytes(Message);
- try
- {
- Stream.Write(WriteBuffer, 0, WriteBuffer.Length);
- }
- catch
- {
- Console.WriteLine("[ERROR] Some error occured. Maybe try again?");
- }
- }
- }
- static void SendPingPong()
- {
- String Message = "PING";
- byte[] buffer = Encoding.Unicode.GetBytes(Message);
- try
- {
- Stream.Write(buffer, 0, buffer.Length);
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- }
- static void Init(bool IsRestarting)
- {
- if(IsRestarting)
- {
- }
- Console.Write("Enter server IP:");
- Host = Console.ReadLine();
- Console.Write("Enter server port:");
- Port = Convert.ToInt32(Console.ReadLine());
- Console.Write("Enter ur username:");
- UserName = Console.ReadLine();
- Client = new TcpClient();
- InitializeSocket();
- InitializeConnection();
- SendMessages();
- Disconnect();
- }
- static void Main(string[] args)
- {
- Init(false);
- }
- }
- }
Add Comment
Please, Sign In to add comment