我有一个服务器 - 客户端套接字代码,当在同一网络上打开服务器和客户端时,它的工作正常,但如果我尝试在不同的网络上运行它们,他们就是不认识对方。 可能是什么问题?
服务器:
public static TcpListener listen;
static void Main(string[] args)
{
Console.Title = "Server";
listen = new TcpListener(8080);
listen.Start();
Console.WriteLine("Wait For Connect");
Socket s = listen.AcceptSocket();
Console.WriteLine("Client Has Been Connected");
read r = new read(s);
Thread t = new Thread(new ThreadStart(r.Reading));
t.Start();
NetworkStream st = new NetworkStream(s);
StreamWriter sw = new StreamWriter(st);
sw.AutoFlush = true;
string massege;
while (true)
{
massege = "server" + ":" + Console.ReadLine();
sw.WriteLine(massege);
}
}
class read
{
private StreamReader sr;
public read(Socket s)
{
Stream a = new NetworkStream(s);
this.sr = new StreamReader(a);
}
public void Reading()
{
while (true)
{
try
{
Console.WriteLine(sr.ReadLine());
}
catch
{
Console.WriteLine("Client Has Disconnected");
// Console.ReadKey();
Socket s = listen.AcceptSocket();
Console.WriteLine("Client Has Been Connected");
}
}
}
}
}
客户端:
static void Main(string[] args)
{
Console.Title = "Client";
bool connect = false;
while (!connect)
{
try
{
TcpClient t = new TcpClient();
t.Connect("192.168.43.36", 8080);
Console.WriteLine("Connect!");
connect = true;
NetworkStream ns = t.GetStream();
read r = new read(t);
Thread tr = new Thread(new ThreadStart(r.startread));
tr.Start();
StreamWriter sw = new StreamWriter(ns);
sw.AutoFlush = true;
string massege;
while (true)
{
massege = "client" + ":" + Console.ReadLine();
sw.WriteLine(massege);
}
}
catch
{
Console.WriteLine("Connection Faild!");
connect = false;
}
}
}
class read
{
StreamReader sr;
public read(TcpClient t)
{
Stream s = t.GetStream();
this.sr = new StreamReader(s);
}
public void startread()
{
while (true)
{
try
{
string s = sr.ReadLine();
Console.WriteLine(s);
}
catch
{
Console.WriteLine("Server Error");
Console.Read();
}
}
}
}
}
感谢您的帮助。
答案 0 :(得分:0)
根据您的描述真的很难对正在发生的事情进行故障排除。但这里列出了我要做的事情:
如果你实际上在NAT / PAT设备后面,你可以安装端口转发和/或将你的服务器pc放在非军事区。