0
Answer

socket programming send recieve string from server to client

jesper

jesper

10y
1.1k
1
Hi,
 
I have a question about socket programming. i need a server/client solution where i'm able to send text string from the server to the client and from client to the server.
 
i have figured out this:
 
Server:
 
static void Main(string[] args)
{
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sck.Bind(new IPEndPoint(0, 1994));
sck.Listen(0);

Socket acc = sck.Accept();

while (true)
{
Console.Write("Write a message");
string msg = Console.ReadLine();

byte[] msgBuffer = Encoding.Default.GetBytes(msg);
acc.Send(msgBuffer, 0, msgBuffer.Length, 0);

byte[] buffer = new byte[255];
int rec = acc.Receive(buffer, 0, buffer.Length, 0);

Array.Resize(ref buffer, rec);

Console.WriteLine("Recived: {0}", Encoding.Default.GetString(buffer));
}
}
 
Client:
 
static void Main(string[] args)
{
Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.1.61"), 1994);
sck.Connect(endPoint);

while (true)
{
Console.Write("Skriv en besked: ");
string msg = Console.ReadLine();
byte[] msgBuffer = Encoding.Default.GetBytes(msg);
sck.Send(msgBuffer, 0, msgBuffer.Length, 0);

byte[] buffer = new byte[255];
int rec = sck.Receive(buffer, 0, buffer.Length, 0);

Array.Resize(ref buffer, rec);

Console.WriteLine("Recived: {0}", Encoding.Default.GetString(buffer));
}

Console.Read();

}
 
 
it dosent work correctly, when the client connects i cannot send a message before the client have sended to me. and when the client have sended a message to me, the client is able to see me message from before.
 
hope that not too confusing /: