Reputation: 1455
I have c# code which is connecting to localhost ip address 127.0.0.1 and port no. 5939. Connection is happening perfectly but it is not receiving any data. I want it to receive data and save it to text file on my local machine.
Does it not receiving data because it is on the localhost and on the same machine or there is error in my code ..
Here is my code..
byte[] data = new byte[1024];
string input, stringData;
String ip = "127.0.0.1";
Int32 port = 5939;
string path = "D://ipdata.text";
if (File.Exists("D://ipsettings.txt"))
{
File.Delete("D://ipsettings.txt");
}
IPAddress ipad = IPAddress.Parse(ip);
IPEndPoint ipend = new IPEndPoint(ipad, port);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
sock.Connect(ipend);
}
catch (Exception ex)
{
throw ex;
}
try
{
int recv = sock.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
while (true)
{
input = "Client here";
sock.Send(Encoding.ASCII.GetBytes(input));
data = new byte[1024];
recv = sock.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
string df = "";
try
{
System.IO.FileInfo fi = new System.IO.FileInfo(path);
My program is not executing after this line..
int recv = sock.Receive(data);
Please help me to get out of this situation. Thanks in advance.
Upvotes: 0
Views: 2048
Reputation: 26209
You need to read the data until unless the Receive function gives you.
use while
loop to determine whether data
is available or not.
int recv=0;
byte[] data = new byte[1024];
StringBuilder sb= new StringBuilder();
while ((recv=sock.Receive(data)) > 0)
{
sb.Append(Encoding.ASCII.GetString(data, 0, recv));
}
Upvotes: 2