c中socket的通信问题
各位大神,我在编一个通信的程序,程序在服务端和客户端自己的电脑上运行正确,在学校的内网的两个不同的电脑上也运行正确,但是在外网的两个机子上就出现“由于目标主机积极拒绝,无法连接“的问题,怎么解决啊,各位大神帮帮忙吧,急啊主要代码如下: #region
IPAddress[]ip;
int length;
TcpListener tcplistener;
TcpListener filetcplistener;
Socket sendsocket;
Socket receivesocket;
Socket filereceivesocket;
Socket filesendsocket;
AsyncCallback callback;
AsyncCallback filecallback;
IPEndPoint localendpoint;
IPEndPoint remoteendpoint;
IPEndPoint filelocalendpoint;
IPEndPoint fileremoteendpoint;
Thread[] th = new Thread[4];
string requestmessage;
string receivestring;
string responsemessage;
string filereceivestring;
string filestringtosend;
string title;
string iptemp;
string counteripstring;
string filepath;
string filename;
string savedfilepath;
string startstring;
delegate void showmessage(string str);
delegate void resume();
delegate void show();
byte[] bytestosend;
byte[] bytesreceived = new byte[8192];
byte[] filebytestosend;
byte[] filebytesreceived = new byte[2048000];
long sendfilelength;
long receivedfilelength;
int receivedlengthtemp;
int sendlengthtemp;
long temp = 0;
long temp2 = 0;
public Form1()
{
InitializeComponent();
try
{
string str = Dns.GetHostName();
ip = Dns.GetHostAddresses(str);
//用来传送文本的本地网络端点
localendpoint = new IPEndPoint(ip[0], 2000);
//用来传送文件的本地网络端点
filelocalendpoint = new IPEndPoint(ip[0], 4000);
callback = new AsyncCallback(startreceivesocket);
filecallback = new AsyncCallback(startfilereceivesocket);
tcplistener = new TcpListener(localendpoint);
filetcplistener = new TcpListener(filelocalendpoint);
this.textBox1.AppendText("请选择监听或者主动连接!\r\n请确保对方处于监听状态才可发出连接申请!\r\n否则需重启这个程序!\n");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//监听的时候打开
private void openth0()
{
th[0] = new Thread(new ThreadStart(th0process));
th[0].IsBackground = true;
if (th[0].IsAlive == false)
th[0].Start();
}
//连接的时候打开
private void openth1()
{
th[1] = new Thread(new ThreadStart(th1process));
th[1].IsBackground = true;
if (th[1].IsAlive == false)
th[1].Start();
}
private void showmessagetotextbox1(string str)
{ //听方,等待被连接的那一方的监听程序
private void th0process()
{
while (true)
{
try
{
if (receivesocket != null)
{
receivesocket.Blocking = true;
length = receivesocket.Receive(bytesreceived, bytesreceived.Length, 0);
receivestring = System.Text.Encoding.GetEncoding("GB2312").GetString(bytesreceived, 0, length);
this.Invoke(new showmessage(showmessagetotextbox1), new object[] { receivestring });
if (receivestring.Length > 9)
if (receivestring.Substring(0, 9) == "对方断开了当前连接")
{
this.Invoke(new resume(resumefunction));
closefunction();
}
if (receivestring.Length > 12)
if (receivestring.Substring(0, 12) == "对方取消了发送文件的请求")
{
this.Invoke(new resume(resumefilefunction));
closefilefunction();
}
if (receivestring == "对方拒绝了您传送文件的请求!")
{
this.Invoke(new resume(resumefilefunction));
closefilefunction();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
//发方,主动连接的那一方的监听程序
private void th1process()
{
while (true)
{
try
{
if (sendsocket != null)
{
sendsocket.Blocking = true;
length = sendsocket.Receive(bytesreceived, bytesreceived.Length, 0);
receivestring = System.Text.Encoding.GetEncoding("GB2312").GetString(bytesreceived, 0, length);
this.Invoke(new showmessage(showmessagetotextbox1), new object[] { receivestring });
if (receivestring.Length > 9)
if (receivestring.Substring(0, 9) == "对方断开了当前连接")
{
this.Invoke(new resume(resumefunction));
closefunction();
}
if (receivestring.Length > 12)
if (receivestring.Substring(0, 12) == "对方取消了发送文件的请求")
{
this.Invoke(new resume(resumefilefunction));
closefilefunction();
}
if (receivestring == "对方拒绝了您的连接请求!")
closefunction();
if (receivestring == "对方拒绝了您传送文件的请求!")
{
this.Invoke(new resume(resumefilefunction));
closefilefunction();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
//连接或接受按钮触发的事件
private void button4_Click_1(object sender, EventArgs e)
{
if (((Button)sender).Text == "连接")
{
try
{
if (sendsocket == null)
{
remoteendpoint = new IPEndPoint(IPAddress.Parse(textBox2.Text), 2000);
sendsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sendsocket.Connect(remoteendpoint);
requestmessage = "IP地址为" + ip[0].ToString() + "的机器想与您通信,您接受吗?";
sendfunction(requestmessage);
this.textBox1.AppendText("您发起了一个连接请求!\n");
if (th[0] != null)
{
if (th[0].IsAlive == true)
this.th[0].Abort();
}
//连接的时候打开
openth1();
//发方,主动连接的那一方的监听线程
}
else
this.textBox1.AppendText("您已经发起了连接请求!正在等待对方应答...\n");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else if (((Button)sender).Text == "接受")
{
try
{
if (receivesocket != null)
{
responsemessage = "对方接受了您的连接请求!";
sendfunction(responsemessage);
this.textBox1.AppendText("您同意了对方的连接请求!\n");
this.textBox2.Text = counteripstring;
title = "已建立连接!";
sendfunction(title);
this.Text = title;
this.button6.Text = "断开连接";
this.button4.Enabled = false;
this.button8.Enabled = false;
this.button1.Enabled = true;
this.button7.Enabled = true;
this.textBox3.Enabled = true;
this.button5.Enabled = true;
if (th[1] != null)
{
if (th[1].IsAlive == true)
this.th[1].Abort();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
c# socket --------------------编程问答-------------------- 请做好服务器对外网的端口映射,如果服务器通过网关连外网的话,对了看你的功能TcpClient足够了为什么选Socket.好像这里的朋友大都喜欢Socket,怱视TcpClient --------------------编程问答-------------------- 我是个新手,没学过这些,但是现在老师要做程序急于解决,大神能帮我改改吗?最好能把具体代码贴出来, --------------------编程问答-------------------- 没有办法,规定用socket写 --------------------编程问答-------------------- 对了,这个程序实现的功能是通信和传输功能 --------------------编程问答-------------------- 看着头晕,给你个我的;
服务端:
IPEndPoint point = new IPEndPoint(IPAddress.Any, port);
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Bind(point);
s.Listen(100);
while (true)
{
Socket accept = s.Accept();
ThreadPool.SetMaxThreads(500, 500);
ThreadPool.QueueUserWorkItem(new WaitCallback(DealWithSocket), accept);
}
客户端:
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 6000);
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 3000);
int port = 8889;IPEndPoint server = new IPEndPoint(IPAddress.Parse(arr[0]), port);
s.Connect(server);
byte[] sendMsg = System.Text.Encoding.UTF8.GetBytes("head:" + GeneralSystemLoginInfo.UserID + "@" + ClientID + ":end");
while (true)
{
s.Send(sendMsg);
byte[] receiveMsg = new byte[1024];
s.Receive(receiveMsg);
if (IsCancel)
{
return;
}
Thread.Sleep(3000);
}
补充:.NET技术 , C#