Reputation: 2891
These are my first steps with client-server communication via TCP in C#. Server is stuck after "Waiting for Client..." message. Client shows "Error: Not Connected to server". What's wrong?
Server code:
using System;
using System.Net;
using System.Net.Sockets;
namespace MyTCPServer
{
public class MyTCPServerClass
{
public static void Main(string[] args)
{
TcpListener listener = null;
int servPort = 55437;
try
{
listener = new TcpListener(IPAddress.Any, servPort);
listener.Start();
}
catch (SocketException se)
{
Console.WriteLine(se.ErrorCode + ": " + se.Message);
Environment.Exit(se.ErrorCode);
}
TcpClient client = null;
NetworkStream netStream = null;
try
{
Console.WriteLine("Waiting for Client...");
client = listener.AcceptTcpClient();
Console.WriteLine("Get Stream...");
netStream = client.GetStream();
Console.Write("Handling client - ");
int bytesRcvd;
int totalBytesEchoed = 0;
byte[] rcvBuffer = new byte[10000];
while ((bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0)
{
netStream.Write(rcvBuffer, 0, bytesRcvd);
totalBytesEchoed += bytesRcvd;
}
Console.WriteLine("echoed {0} bytes.", totalBytesEchoed);
netStream.Close();
client.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
netStream.Close();
}
}
}
}
Client code:
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
namespace MyTCPClient
{
/// <summary>
/// Demonstration eines synchron agierenden TcpClienten.
/// </summary>
public class MyTCPClientClass
{
static void Main(string[] args)
{
byte[] byteBuffer = Encoding.ASCII.GetBytes("Hello World");
//IPAddress ipAddress = IPAddress.Parse("192.168.1.16");
IPAddress ipAddress = IPAddress.Loopback;
int servPort = 55437;
TcpClient client = null;
NetworkStream netStream = null;
try {
client = new TcpClient(new IPEndPoint(ipAddress, servPort));
if (!client.Connected)
{
Console.WriteLine("Error: Not Connected to server");
throw new Exception();
}
else Console.WriteLine("Connected to server... sending echo string");
netStream = client.GetStream();
netStream.Write(byteBuffer, 0, byteBuffer.Length);
Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);
int totalBytesRcvd = 0;
int bytesRcvd = 0;
while (totalBytesRcvd < byteBuffer.Length) {
if ((bytesRcvd = netStream.Read(byteBuffer, totalBytesRcvd,
byteBuffer.Length - totalBytesRcvd)) == 0) {
Console.WriteLine("Connection closed prematurely.");
break;
}
totalBytesRcvd += bytesRcvd;
}
Console.WriteLine("Received {0} bytes from server: {1}", totalBytesRcvd,
Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
finally {
if (netStream != null) netStream.Close();
if (client != null) client.Close();
}
Console.ReadKey(true);
}
}
}
Upvotes: 1
Views: 881
Reputation: 1062502
client = new TcpClient();
client.Connect(new IPEndPoint(ipAddress, servPort));
Upvotes: 1