Cześć.
Mam problem z napisaniem programów klient i serwer.
Chcę, aby program serwer po podłączeniu się klienta wysłał wiadomość, następnie klient ją odebrał i po tym zaczął wysyłać "swoje" wiadomości".
Niestety coś mi nie wychodzi, udało się jedynie zrealizować drugą część (klient nadaje, serwer odbiera).
Serwer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace NEW_SERV
{
class Program
{
static void Main(string[] args)
{
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sck.Bind(new IPEndPoint(0, 1234));
sck.Listen(100);//maksymalna ilosc polaczen oczekujacych
Socket accepted;
//Tworzymy gniezdo nasłuchu które czaka na jakieś dane wysłane od jakiegoś klienta
string strData=string.Empty;
Console.ReadKey();
byte[] data = Encoding.ASCII.GetBytes("transmituj!");
sck.Send(data);
accepted = sck.Accept();
while (strData != "quit")
{
byte[] Buffer = new byte[accepted.SendBufferSize];
int bytesRead = accepted.Receive(Buffer);
byte[] formatted = new byte[bytesRead];
for (int i = 0; i < bytesRead; i++)
formatted[i] = Buffer[i];
strData = Encoding.ASCII.GetString(formatted);
Console.Write(strData + "\n");
}
Console.Read();
//zamknięcie gniazda
sck.Close();
}
}
}
Klient
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace NEW_CLIENT
{
class Program
{
static void Main(string[] args)
{
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket sck2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);
try
{
sck.Connect(localEndPoint);
}
catch
{
Console.Write("nie można połączyć");
Main(args);
}
sck2.Bind(new IPEndPoint(0, 1234));
sck2.Listen(100);
string text = string.Empty;
Socket accepted = sck2.Accept();
byte[] Buffer = new byte[accepted.SendBufferSize];
int bytesRead = accepted.Receive(Buffer);
byte[] formatted = new byte[bytesRead];
for (int i = 0; i < bytesRead; i++)
formatted[i] = Buffer[i];
//formatujemy dane do stringa
string strData = Encoding.ASCII.GetString(formatted);
Console.Write(strData + "\n---------------+\n");
while (text != "quit")
{
Console.Write("Podaj tekst: ");
text = Console.ReadLine();
byte[] data = Encoding.ASCII.GetBytes(text);
sck.Send(data);
}
Console.WriteLine("Koniec programu");
Console.Read();
sck.Close();
}
}
}
Proszę o pomoc :(