上網自學了一點C# 但不是很理解
我想用C#做一個Server 和 Clinet
用別人的範例可以做到同網段下通信, 但要是網段不同就連不上了, 網路上搜尋到使用UPnp來解決
參考網站
https://blog.csdn.net/yangyifan0/article/details/52295253
不曉得哪裡寫錯了, 想請問要怎麼修改能解決不同網段可以通信的問題呢
Server端程式碼
IPAddress ipv4;
String eip;
int iport = 8733;
int eport = 8733;
static Socket socketListener;
public Form1()
{
InitializeComponent();
String name = Dns.GetHostName();
ipv4 = Dns.GetHostEntry(name).AddressList.Where(i => i.AddressFamily == AddressFamily.InterNetwork).FirstOrDefault();
WebClient webClient = new WebClient();
HttpClient client = new HttpClient();
String rawRes = webClient.DownloadString("http://checkip.dyndns.org/");
String regex = @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b";
eip = Regex.Match(rawRes, regex).Value;
OpenUPnp();
ServerEnd(eport, 10);
Thread th = new Thread(ServerCommunity);
th.Start(socketListener);
}
private Boolean OpenUPnp()
{
UPnPNAT uPnPNAT = new UPnPNAT();
IStaticPortMappingCollection mapping = uPnPNAT.StaticPortMappingCollection;
if (mapping == null)
{
return false;
}
mapping.Add(eport, "TCP", iport, ipv4.ToString(), true, "測試");
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(new IPEndPoint(ipv4, iport));
IList<ServicePoint> servicePoints = new List<ServicePoint>();
return true;
}
private static void ServerCommunity(object obListener)
{
Socket temp = (Socket)obListener;
while (true)
{
Socket socketSender = temp.Accept();
logd("ServerCommunity()", ("Client IP = " + socketSender.RemoteEndPoint.ToString()) + " Connect Succese!");
Thread ReceiveMsg = new Thread(ReceiveClient);
ReceiveMsg.IsBackground = true;
Thread SendToClient = new Thread(SendMsgToClient);
SendToClient.Start(socketSender);
ReceiveMsg.Start(socketSender);
}
}
Client端程式碼
IPAddress ipv4;
String eip;
int iport = 8733;
int eport = 8733;
static Socket socketListener;
public Form1()
{
InitializeComponent();
String name = Dns.GetHostName();
ipv4 = Dns.GetHostEntry(name).AddressList.Where(i => i.AddressFamily == AddressFamily.InterNetwork).FirstOrDefault();
WebClient webClient = new WebClient();
HttpClient client = new HttpClient();
String rawRes = webClient.DownloadString("http://checkip.dyndns.org/");
String regex = @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b";
eip = Regex.Match(rawRes, regex).Value;
ClientSocket(ipv4.ToString(), iport);
}
private static void ClientSocket(string ip, int port)
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress myIp = IPAddress.Parse(ip);
IPEndPoint point = new IPEndPoint(myIp, port);
socket.Connect(point);
logd("ClientSocket(" + ip + ", " + port+")", "Connect Succese! " + socket.RemoteEndPoint.ToString());
Thread sendMsg = new Thread(SendMsgToServer);
Thread ReceiveMsg = new Thread(ReceiveMsgFromServer);
ReceiveMsg.IsBackground = true;
ReceiveMsg.Start();
sendMsg.Start();
}
感激不盡