日期:2014-05-18  浏览次数:20900 次

C/S结构程序分别在两台电脑上无法连接?????
//echo服务器程序代码
using System;
using System.Net;
using System.Net.Sockets;

class echoserver
{
 public static void Main()
 {
  Socket serversocket,theconnect;
  IPHostEntry hostaddr;
  IPEndPoint myhost;
//获取本地计算机的名字
  serversocket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
  String hostname=Dns.GetHostName();
  hostaddr=Dns.Resolve(hostname);
  try
  {
  myhost=new IPEndPoint(hostaddr.AddressList[0],7);
  }
  catch(ArgumentException)
  {
  Console.WriteLine("通信端口号错误!");
  return;
  }
  try
  {
  serversocket.Bind(myhost);
  serversocket.Listen(100);
  }
  catch(SocketException)
  {
  Console.WriteLine("绑定不成功!");
  return;
  }
  Console.WriteLine("服务器创建成功!");
  Console.WriteLine("正在等候客户端的连接`````````");
  while(true)
  {
  theconnect=serversocket.Accept();
  printclientinfo((IPEndPoint)theconnect.RemoteEndPoint);
  int bytes=0;
  Byte[] recvbyte=new Byte[256];
  while(true)
  {
  try
  {
  bytes=theconnect.Receive(recvbyte,recvbyte.Length,0); 
  } 
  catch(SocketException)
  {
  Console.WriteLine("无法接收到数据!");
  break;
  }
  if(bytes==0)
  {break;}

  try
  {
  theconnect.Send(recvbyte,bytes,0);
  }
  catch(SocketException)
  {
  Console.WriteLine("数据发送出错!");
  break;
  }
  }
  theconnect.Close();
  Console.WriteLine("与客户端断开````````");
  }
}
public static void printclientinfo(IPEndPoint clientipe)
{
 IPAddress clientip=clientipe.Address;
 Console.WriteLine("我的客户端IP地址是: "+clientip.ToString());
 }
}

//echo客户端程序
  IPAddress hostaddr=IPAddress.Parse(args[0]);
//通过IPAddress对象和端口号创建一个IPEndPoint对象
  IPEndPoint hostip=new IPEndPoint(hostaddr,7);
//声明一个Socket对象
  Socket s=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
  try
  {
//与指定服务器连接
  s.Connect(hostip);
  }
  catch(SocketException)
  {
//连接不成功,将显示下面的信息
  Console.WriteLine("连接不成功!");
//退出程序
  return;
  }
  Console.WriteLine("成功连接!!!!");
  String tempstr="";
  while(true)
  {
  tempstr=Console.ReadLine();
//若用户输入exit则退出程序
  if(tempstr.Equals("exit"))  
  break;

  Byte[] sendbyte=Encoding.ASCII.GetBytes(tempstr.ToCharArray());
  try
  {
  s.Send(sendbyte,sendbyte.Length,0);
  }
  catch(SocketException)
  {
  Console.WriteLine("发送数据不成功!");
  }
  int bytes=0;
  Byte[] recvbyte=new Byte[256];
  String recvstr="";
  try
  {
  bytes=s.Receive(recvbyte,recvbyte.Length,0);
  }
  catch(SocketException)
  {
  Console.WriteLine("接收数据不成功!");
  }
 // Console.WriteLine("接收数据成功 :");
  recvstr=Encoding.ASCII.Ge