When Using NetworkStream data not recieved over basic tcp interface - c#

I'm creating a basic TicTacToe program to play against my friends across the internet (this is to learn the basics of network programming). The problem is that although the correct data is received by the client, when it tries to send data no data is sent, even though the code executes correctly.
Here is the client software:
string input;
Board board = new Board();
while (true)
{
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect("192.168.0.10", 5000);
byte[] b = new byte[1024];
NetworkStream ns = tcpclnt.GetStream();
int k = ns.Read(b, 0, 100);//recieve data from host
string sRecieve = string.Empty;
for (int i = 0; i < k; i++)
sRecieve += Convert.ToChar(b[i]);
Console.WriteLine(sRecieve);
input = Console.ReadLine();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(input);
ns.Write(ba, 0, ba.Length);
tcpclnt.Close();
}
This is the server code (this is all that is running when the connection occurs):
TcpListener tcpList = new TcpListener(IPAddress.Any, 5000);
tcpList.Start();
Console.WriteLine("Waiting for valid connection");
Socket s = tcpList.AcceptSocket();
Console.WriteLine("Connection accepted from: " + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(board.ToString()));//send data
Console.WriteLine("sent board layout");
byte[] b = new byte[1024];
Console.WriteLine("Waiting for next play");
int k = s.Receive(b);
Console.WriteLine("Received next play");
string sInput = string.Empty;
for (int i = 0; i < k; i++)
input += Convert.ToChar(b[i]);

Related

Problem socket TCP IP in C# received only one message from client before stop

I've a problem with my server in tcp/ip, because after received one message doesn't work.
I don't know if use a while true, and how to put it.
Any suggestion?
Thank you
my method()
sdk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sdk.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8052));
sdk.Listen(10);
Socket accepted = sdk.Accept();
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];
}
Debug.Log("\t Server" + "\n");
string stradata = Encoding.ASCII.GetString(formatted);
Debug.Log("-->" + "" + stradata + "\n\n");
testo = stradata;
//sdk.Close(); tried to uncomment
//accepted.Close(); tried to uncomment
You need to read from the socket continually, until you have read all the data that you want
sdk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sdk.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8052));
sdk.Listen(10);
Socket accepted = sdk.Accept();
Buffer = new byte[accepted.SendBufferSize];
while (true)
{
// begin reading continually from the socket
// Socket::Receive() will block until it gets some data
// Exception handling required here for when client closes connection
int bytesRead = accepted.Receive(Buffer);
byte[] formatted = new byte[bytesRead];
for (int i = 0; i < bytesRead; i++)
{
formatted[i] = Buffer[i];
}
Debug.Log("\t Server" + "\n");
string stradata = Encoding.ASCII.GetString(formatted);
Debug.Log("-->" + "" + stradata + "\n\n");
// Need to add some exit logic here eg,
if(stradata.Contains("EXIT"))
break;
}
sdk.Close();
accepted.Close();

Socket communication output issue

In getting used to Sockets using Client server communication here is my code.
//server partl
try
{
IPAddress ipAd = IPAddress.Parse("127.0.0.1"); //use local m/c IP address, and use the same in the client
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 8020);
/* Start Listeneting at the specified port */
myList.Start();
Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
//Console.WriteLine("Recieved...");
//Writes to label1
for (int i = 0; i < k; i++)
label1.Text = b[i].ToString();
//ASCII endoing to use ACK.
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
/* clean up */
s.Close();
myList.Stop();
}
catch (Exception ex)
{
Console.WriteLine("Error..... " + ex.StackTrace);
}
//Client part
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("127.0.0.1", 8020); // use the ipaddress as in the server program
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
//gets the text from textbox
String str = textBox1.Text;
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba, 0, ba.Length);
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(bb[i]));
tcpclnt.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error..... " + ex.StackTrace);
}
}
I am using a form to communicate on local host and writing a one .cs file and want to show the text(from textbox) from Client-labelled portion to the label on server-labelled portion.
Any idea why its not showing output?. New to sockets !!!
When socket receives the data instead of loop simply use this:
if (k > 0)
label1.Text = Encoding.UTF8.GetString(b);
Also you can use this for simply send and receive data using TcpClient which is a wrapper around socket.

simple implementation of a TCP client server relationship

I have a simple implementation of a TCP client server relationship. But their are few problems that i don't know how to fix. here is the code of the Client and Server:
Client and Server are both separated. Each one of them is written i different project.
public void Server()
{
try
{
IPAddress IP = IPAddress.Parse("127.0.0.1");
TcpListener Listener = new TcpListener(IP, 8001);
Listener.Start();
Socket s = Listener.AcceptSocket();
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++){
ConsoleWpfGUI.Write(Convert.ToChar(b[i]));
}
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string:"+strTemp+ " was recieved by the server."));
s.Close();
Listener.Stop();
}
catch (Exception e) {
ConsoleWpfGUI.WriteLine("Error..... " + e.StackTrace);
}
}
}
public void Client()
{
try
{
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect("127.0.0.1", 8001);
String str = InputString.Text;
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
stm.Write(ba, 0, ba.Length);
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
for (int i = 0; i < k; i++)
ConsoleWpfGUI.Write(Convert.ToChar(bb[i]));
tcpclnt.Close();
}
catch (Exception e)
{
ConsoleWpfGUI.Text = "No connection..... ";
}
}
}
1. The listener does not work properly, i.e. the listening captures the GUI thread (serv and client classes that i use in wpf). and not running in a separate thread, resulting with the application being unresponsive once “listen” (Buttoon that start the class serv) is pressed.
Only with the 1st call being replied it's work,the next send is fails. resulting not dealing with the socketing and passing to a separate thread right on the server side.
How can I use Thread that the serv class will not stuck the app.
And how i can use properly with socketing and passing threads that will make my app work more then ones.
Thanks!
You need to use separate threads for "Client" and "Server". You cannot run both in one UI thread. Because listening will block your UI thread and hence neither Client or Server can run correctly.
You can find many resources over internet about Client Server practice examples. Just use Threading, Background Workers for accomplish your task
Good Articles :
http://csharp.net-informations.com/communications/csharp-socket-programming.htm
http://www.codeproject.com/Tips/607801/SimpleplusChatplusprogramplusinplusC ,
http://www.codeproject.com/Articles/99143/BackgroundWorker-Class-Sample-for-Beginners
I ran your code. Try running following on TWO Console programs - Rub them Separately and run Server first
Client -
try
{
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect("127.0.0.1", 8001);
String str = "From CLient";
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
stm.Write(ba, 0, ba.Length);
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(bb[i]));
tcpclnt.Close();
}
catch (Exception)
{
Console.WriteLine("No connection..... ");
}
Console.WriteLine("Transmission end.");
Console.ReadKey();
Server -
string strTemp = "Hello from server";
try
{
IPAddress IP = IPAddress.Parse("127.0.0.1");
TcpListener Listener = new TcpListener(IP, 8001);
Listener.Start();
Socket s = Listener.AcceptSocket();
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
{
Console.Write(Convert.ToChar(b[i]));
}
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string:" + strTemp + " was recieved by the server."));
s.Close();
Listener.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
Console.ReadKey();
Note - Just paste them inside Main method and try, you will need Sytem.IO import in Visual Studio ()

Reading data from a TCP Socket not getting all of the data

I am working on a C# and android client/server application.
Android is sending a message to C# and I can see it is sending the correct data, however C# doesn't receive all of it.
Below is the code I have in C#
TcpListener tcpListener = new TcpListener(IPAddress.Any, serverTCPPort);
tcpListener.Start();
while (true)
{
tcpClient = tcpListener.AcceptTcpClient();
stream = tcpClient.GetStream();
reader = new StreamReader(stream);
writer = new StreamWriter(stream);
writer.NewLine = "\r\n";
writer.AutoFlush = true;
byte[] serverData = new byte[tcpClient.ReceiveBufferSize];
int length = stream.Read(serverData, 0, serverData.Length);
string received = Encoding.ASCII.GetString(serverData, 0, length);
}
Below is how I am sending the data via Android
i
f (contactInformation.photoBase64String != null) {
bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), Uri.parse(contactInformation.photoBase64String));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
bitmap64Encoded = Base64.encodeToString(b, Base64.DEFAULT);
}
Toast.makeText(context, "Incoming call from " + contactInformation.contactName, Toast.LENGTH_LONG).show();
XmlSettings xmlSettings = new XmlSettings();
xmlSettings.setIndent(true);
XmlWriter xmlWriter = new XmlWriter(xmlSettings);
xmlWriter.writeStartDocument();
xmlWriter.writeStartElement("StatusManager");
xmlWriter.writeElementString("Command", Defines.ServerCommands.IncomingCall.toString());
xmlWriter.writeStartElement("CallInformation");
xmlWriter.writeElementString("PhoneNumber", phoneNumber);
xmlWriter.writeElementString("ContactName", contactInformation.contactName);
if (contactInformation.photoBase64String != null)
{
xmlWriter.writeElementString("PhotoUri", bitmap64Encoded);
}
xmlWriter.writeEndElement();
xmlWriter.writeEndElement();
String xml = xmlWriter.returnXmlOutput();
TCPSender tcpSender = new TCPSender(context, DeviceManagement.servers.get(0), xmlWriter.returnXmlOutput());
Thread thread = new Thread(tcpSender);
thread.start();
The TCP Sender is
#Override
public void run() {
Log.d("TCPSender", xml);
HelperClass helperClass = new HelperClass();
try
{
Socket socket = new Socket(foundServerInformation.ipAddress, foundServerInformation.tcpServerPort);
OutputStream out = socket.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println(xml);
output.flush();
I guess the data is too big for the byte array but I can't find a way of how to ensure I get all of the information that Android is sending.
It's difficult to know where the problem might be (I see your code is OK), but here you have a working example from Microsoft how it should be done, maybe it gives you some clues.
TcpListener server=null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while(true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while((i = stream.Read(bytes, 0, bytes.Length))!=0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
client.Close();
}
}
catch(SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
I've finally managed to get it working, it was something to do with using the SendReceiveBuffer which I did try but didn't work but now it does so I guess I missed something.
Below is the code I am using to receive all of the data
TcpListener tcpListener = new TcpListener(IPAddress.Any, serverTCPPort);
tcpListener.Start();
string received = "";
while (true)
{
tcpClient = tcpListener.AcceptTcpClient();
stream = tcpClient.GetStream();
reader = new StreamReader(stream);
writer = new StreamWriter(stream);
writer.NewLine = "\r\n";
writer.AutoFlush = true;
byte[] bytes = new byte[tcpClient.SendBufferSize];
int recv = 0;
while (true)
{
recv = stream.Read(bytes, 0, tcpClient.SendBufferSize);
received += System.Text.Encoding.ASCII.GetString(bytes, 0, recv);
if (received.EndsWith("\n\n"))
{
break;
}
}
}

how to send and receive string continously using sockets in c#

Basically what i am stuck at is , i want my client to send data continously and server to read from client as it sends, like when i send "2" it should read "2" and display and so on it should continue to read as long as i send from the client, i can stop or exit whenever i press some different character,.
what i have acheived is not continous, i send from client 2 and server receives 2 and then it is stopped, i want to send them continously , i am pasting below my code,
client.cs
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace Client
{
class Program
{
const int port = 8001;
const string ip = "127.0.0.1";
const int maxBuffer = 100;
static void Main(string[] args)
{
try
{
while (true)
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("127.0.0.1", 8001);
// use the ipaddress as in the server program
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
String str = Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba, 0, ba.Length);
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(bb[i]));
Console.ReadLine();
tcpclnt.Close();
}
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
}
server.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Server
{
class Program
{
const int port = 8001;
const string ip = "127.0.0.1";
const int maxBuffer = 100;
static void Main(string[] args)
{
try
{
IPAddress ipAd = IPAddress.Parse("127.0.0.1");
// use local m/c IP address, and
// use the same in the client
while (true)
{
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 8001);
/* Start Listeneting at the specified port */
myList.Start();
Console.WriteLine("The server is running at port 8001...");
Console.WriteLine("The local End point is :" +
myList.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("Recieved...");
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
Console.ReadLine();
/* clean up */
s.Close();
myList.Stop();
}
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
}
Any help will be appreciated
Thanks :)
By using MultiThread you can send and receive message between client and server continuously.
Server side example:
IPAddress[] ipAdd = Dns.GetHostAddresses("192.168.1.38");
IPAddress ipAddress = ipAdd[0];
TcpListener serverSocket = new TcpListener(ipAddress, 8888);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
notifyIcon.ShowBalloonTip(5000, "Server Notification", " >> Server Started.", wform.ToolTipIcon.Info);
counter = 0;
while (true)
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
if (clientsList.ContainsKey(dataFromClient))
{
continue;
}
else
{
clientsList.Add(dataFromClient, clientSocket);
}
string onlineUsers = "";
foreach (DictionaryEntry item in clientsList)
{
onlineUsers += item.Key.ToString() + ";";
}
onlineUsers = onlineUsers.Remove(onlineUsers.Length - 1);
Broadcast.BroadcastSend(dataFromClient + " joined. |" + onlineUsers, dataFromClient, ref clientsList, false, false);
notifyIcon.ShowBalloonTip(5000,"Client Notification", dataFromClient + " joined.", wform.ToolTipIcon.Info);
HandleClient client = new HandleClient();
client.StartClient(clientSocket, dataFromClient, clientsList, notifyIcon);
}
More details
Ignore my earlier answer
The problem is that the server is waiting for user response in console after sending acknowledgement.
Console.ReadLine();
Just comment out this line in your original program.
And add a exit condition by checking the input.
Also as the previous poster suggest, make it thread based if you want multiple clients connecting to this server simultaneously.

Categories