由于目标机器积极拒绝,无法连接的问题!
using System;using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
class Client {
public static void Main(String[] args) {
TcpClient tcpc = new TcpClient();
Byte[] read = new Byte[32];
if (args.Length != 1) {
Console.WriteLine("Please specify a server name in the command line");
return;
}
String server = args[0];
// Verify that the server exists
try
{
IPHostEntry ipInfo = Dns.GetHostByName(server);
}
catch (SocketException socketExcep) {
Console.WriteLine("Cannot find server: " + server + "\nException:\n" + socketExcep.ToString());
return;
}
// Try to connect to the server
tcpc.Connect(server, 14);
// Get the stream
Stream s;
try
{
s = tcpc.GetStream();
}
catch (InvalidOperationException)
{
Console.WriteLine("Cannot connect to server {0}", server);
return;
}
// Read the stream and convert it to ASII
int bytes = s.Read(read, 0, read.Length);
String Time = Encoding.ASCII.GetString(read);
// Display the data
Console.WriteLine("Received " + bytes + " bytes");
Console.WriteLine("Current date and time is: " + Time);
tcpc.Close();
// Wait for user response to exit
Console.WriteLine("Press Enter to exit");
Console.Read();
}
}
运行这段代码之后,运行报错:
未处理的“System.Net.Sockets.SocketException”类型的异常出现在 system.dll 中。
其他信息: 由于目标机器积极拒绝,无法连接。
请问如何解决? --------------------编程问答-------------------- 1.如果是采用TCP/udp协议进行连接,检查windows防火墙是否开放相应SocketTCP/udp端口;
简单的检测方法是关闭windows防火墙后再试;
2.检查防火墙软件是否开放相应SocketTCP/udp端口;
简单的检测方法是关闭防火墙软件后再试;
3.如果服务器端和客户端均在本机上运行,则将相应的 serverIP="127.0.0.1",serveraddress="127.0.0.1";
服务器端侦听:
listener = new TcpListener(IPAddress.Parse(serverIP), listenport);
listener.Start();
客户端与服务器建立连接:
clientsocket = new TcpClient(serveraddress, serverport);
4.如果服务器运行在局域网或广域网内,则将相应的
serverIP,serveraddress设为本机所在局域网或广域网上的IP;
注意 serverport==listenport;
--------------------编程问答-------------------- 怎么实现你的第三点? --------------------编程问答-------------------- public static void Main(String[] args) {
你的Main有个参数args,下面的程序把它用作服务器地址了
把它改改啊,改成 127.0.0.1 --------------------编程问答-------------------- String server = args[0];
改成
String server="127.0.0.1";
补充:.NET技术 , .NET Framework