日期:2014-05-18 浏览次数:21169 次
//获取远程主机IP public string[] getRemoteIP(string RemoteHostName) { IPHostEntry ipEntry = Dns.GetHostByName(RemoteHostName); IPAddress[] IpAddr = ipEntry.AddressList; string[] strAddr = new string[IpAddr.Length]; for (int i = 0; i < IpAddr.Length;i++ ) { strAddr[i] = IpAddr[i].ToString(); } return(strAddr); }
------解决方案--------------------
哈哈~ 看看这段代码~
服务器端做一个程序,设定好IP地址和端口号,启动Listening事件
客户端直接用TCP/ip协议连接服务器的IP和端口号,发送请求事件,获取返回内容
这个是以前写的一个小程序的代码,你可以看看有没有帮助:
private void StartServer()
{
string strIP = txtServerIP.Text.Trim();
string strPort = txtServerPort.Text.Trim();
string strFolder = this.txtSavePath.Text.Trim();
Regex re = new Regex(@"^([\d]{4,5})$");
Regex re1 = new Regex(@"^\d{2,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$");
if (!re1.Match(strIP).Success)
{
MessageBox.Show("服务器地址错误!");
txtServerIP.Focus();
}
else
{
if (!re.Match(strPort).Success)
{
MessageBox.Show("服务器端口号错误,正确的端口号应为1024-65535之间!");
txtServerPort.Focus();
}
else
{
int intPort = Convert.ToInt32(strPort);
if (intPort < 1024 || intPort > 65535)
{
MessageBox.Show("服务器端口号错误,正确的端口号应为1024-65535之间!");
txtServerPort.Focus();
}
else
{
if (strFolder == "")
{
MessageBox.Show("错误的文件保存路径");
txtSavePath.Focus();
}
else
{
if (!System.IO.Directory.Exists(strFolder))
{
MessageBox.Show("错误的文件保存路径");
txtSavePath.Focus();
}
else
{
if (strFolder.Substring(strFolder.Length - 1, 1) != "\\") strFolder += "\\";
MyServer server = new MyServer();
txtServerIP.Enabled = false;
txtServerPort.Enabled = false;
txtSavePath.Enabled = false;
blnIsOpen = true;
this.button1.Enabled = false;
this.button2.Enabled = true;
listBox1.Items.Clear();
listBox1.Items.Add("正在启动监听......");
server.Folder = strFolder;
server.IP = strIP;
server.Port = intPort;
Thread th = new Thread(new ThreadStart(server.Start));
th.IsBackground = true;
th.Start();
while (blnIsOpen)
{
Application.DoEvents();
string strMsg = server.State;
string strErr = server.Error;
if (strMsg != "")
{
if (listBox1.Items.Count > 100)
{
listBox1.Items.Clear();
}
listBox1.Items.Add(strMsg);
server.State = "";
}
if (strErr != "")
{
txtErr.Text += "\r\n" + System.DateTime.Now + " " + strErr;
server.Error = "";
th.Abort();
intErrNum++;
this.tabPage2.Text = "错误信息(" + intErrNum.ToString() + ")";
}
if (server.NeedReset)
{
//th.Abort();
StartServer();
}
}
}
}
}
}
}
}
public class MyServer
{
string strState = "";
string strErr = "";
string strIP = "";
int intPort = 0;
bool blnClose=false;
TcpListener listener;
string strPath = "";
bool blnNeedReset = false;
public MyServer()
{
blnClose = false;
}
public void Start()
{
strErr = "";
try
{
listener = new TcpListener(IPAddress.Parse(strIP), intPort);
Application.DoEvents();
listener.Start(200);
strState = "启动成功,正在监听是否有连