I am new to C# having spent many years with VB and I'm trying to setup a simple client/Server communication. Th initial socket connection appears to work perfectly however, after the first connection has been setup, the client drops the connection so no more communication can occur.
Server Code
<pre>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Server
{
class Server
{
static void Main(string[] args)
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8221);
s.Bind(ipLocal);
s.Listen(4);
Console.WriteLine("Waiting for client ...\n");
Socket newConnection = s.Accept();
if (newConnection != null)
{
while (true)
{
byte[] buffer = new byte[4096];
try
{
int result = newConnection.Receive(buffer);
if (result > 0)
{
ASCIIEncoding encoder = new ASCIIEncoding();
String recdMsg = encoder.GetString(buffer, 0, result);
byte[] array = Encoding.ASCII.GetBytes("" + recdMsg);
Dungeon dungeon = new Dungeon();
Console.WriteLine("Welcome: " + recdMsg);
int bytesSent = s.Send(buffer);
dungeon.Init();
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex);
}
}
}
}
private string v1 = "Room 0";
private int v2 = 0;
internal static Room Dungeon(string v1, int v2)
{
throw new NotImplementedException();
}
}
}
Client Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Client
{
class client
{
static void Main(string[] args)
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8221);
bool connected = false;
while (connected == false)
{
try
{
s.Connect (ipLocal);
connected = true;
Console.Write("We are connected!\n" , 0);
}
catch (Exception)
{
Console.Write("Failed", 0);
Thread.Sleep (1000);
}
}
int ID = 0;
while (true)
{
String Msg = Console.ReadLine();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes(Msg);
String DunMessage = encoder.GetString(buffer, 0, ID);
Console.WriteLine(DunMessage);
try
{
Console.WriteLine("Writing to server: " + Msg);
int bytesSent = s.Send(buffer);
s.Receive(buffer);
}
catch (System.Exception ex)
{
Console.WriteLine(ex);
}
Thread.Sleep(1000);
}
}
}
}
Can anyone please point out where I'm going wrong?
Thanks
What I have tried:
I can't find anything else to try having established a connection. It's obviously something really basic.