PDA

View Full Version : سوال: برقراری ارتباط با یک port



bade saba
جمعه 14 فروردین 1388, 12:01 عصر
من کد زیر رو از روی کتابی مربوط به socket programming برداشتم اما در خطی که bold کردم در این کد با پیغام خطای No connection could be made because the target machine actively refused it 213.217.39.37:7
مواجه میشم . من برای نام سرور اسم کامپیوتر خودم رو نوشتم از پورت 7 که پیش فرض خود برنامست استفاده کردم می خواستم بدونم ایراد کارم چیه و چه جوری قابل حل است




if (textBox1.Text != "")
{
string[] args = textBox1.Text.Split(' ');



if ((args.Length < 2) || (args.Length > 3))
{ // Test for correct # of args
throw new ArgumentException("Parameters: <Server> <Word> [<Port>]");
}

//String server = args[0]; // Server name or IP address
string server = args[0]; // Server name or IP address

// Convert input String to bytes
byte[] byteBuffer = Encoding.ASCII.GetBytes(args[1]);

// Use port argument if supplied, otherwise default to 7
int servPort = (args.Length == 3) ? Int32.Parse(args[2]) : 7;

TcpClient client = null;
NetworkStream netStream = null;

try
{
// Create socket that is connected to server on specified port
client = new TcpClient(server, servPort);

listBox1.Text = "Connected to server... sending echo string";
//Console.WriteLine("Connected to server... sending echo string");

netStream = client.GetStream();

// Send the encoded string to the server
netStream.Write(byteBuffer, 0, byteBuffer.Length);

listBox1.Text = "Sent " + byteBuffer.Length + " bytes to server...";
Console.WriteLine("Sent {0} bytes to server...", byteBuffer.Length);

int totalBytesRcvd = 0; // Total bytes received so far
int bytesRcvd = 0; // Bytes received in last read

// Receive the same string back from the server
while (totalBytesRcvd < byteBuffer.Length)
{
if ((bytesRcvd = netStream.Read(byteBuffer, totalBytesRcvd,
byteBuffer.Length - totalBytesRcvd)) == 0)
{
listBox1.Text = "Connection closed prematurely.";
Console.WriteLine("Connection closed prematurely.");
break;
}
totalBytesRcvd += bytesRcvd;
}

listBox1.Text = "Received " + totalBytesRcvd + " bytes from server: " + Encoding.ASCII.GetString(byteBuffer, 0, totalBytesRcvd);
//Console.WriteLine("Received {0} bytes from server: {1}", totalBytesRcvd,Encoding.ASCII.GetString(byteBuffer , 0, totalBytesRcvd));

}
catch (Exception e)
{
listBox1.Text = e.Message;
Console.WriteLine(e.Message);
}
finally
{
netStream.Close();
client.Close();
}

}
}

Editali
شنبه 15 فروردین 1388, 02:12 صبح
دوست عزیز من کدتو تست کردم، مشکلی نداشت. احتمالا نرم افزار دیگه ای داره از اون پورت استفاده میکنه.