PDA

View Full Version : سوال: برنامه ی ارسال پیام در سی‌شارپ با کمک server و client



kamran_14
شنبه 20 خرداد 1396, 18:22 عصر
سلام
خسته نباشید
من در C#‎‎‎ برنامه server و client رو نوشتم
من هر وقت برنامه ی server رو اجرا میکنم چون هیچ client ی متصل نیست هنک میکنه. چطوری به سیستم بگم که هر وقت cliet در خواست فرستاد متصل بشه
namespace Server
{
class Program
{IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Listening...");
listener.Start();

//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();

//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];

//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);

//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received : " + dataReceived);

//---write back the text to the client---
Console.WriteLine("Sending back : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
client.Close();
listener.Stop();
Console.ReadLine();
}
}
}

namespace Client
{
class Program
{
const int PORT_NO = 5000;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
//---data to send to the server---
string textToSend = DateTime.Now.ToString();

//---create a TCPClient object at the IP and port no.---
TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
NetworkStream nwStream = client.GetStream();
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);

//---send the text---
Console.WriteLine("Sending : " + textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);

//---read back the text---
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
Console.ReadLine();
client.Close();
}
}
}

_behnam_
شنبه 20 خرداد 1396, 21:23 عصر
سلام. یه نمونه اینجا هستhttp://csharp.net-informations.com/communications/csharp-chat-client.htm

https://codereview.stackexchange.com/questions/79274/tcp-chat-application-with-both-server-and-client-logic-in-same-application