private void button1_Click(object sender, EventArgs e)
{
try
{
int port = 2000;
string host = "192.168.0.127";
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例 c = null;
c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
// c.ReceiveTimeout = 3000;
//ShowMessage("Conneting...");
c.Connect(ipe);//连接到服务器 string sendStr = "hello!This is a socket test";
byte[] bs = Encoding.ASCII.GetBytes(sendStr);
c.Send(bs, bs.Length, 0);//发送测试信息 bytes = c.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
recvStr = Encoding.ASCII.GetString(recvBytes, 0, bytes);
if (recvStr=="nihao")
{
string dd = "nihuai";
byte[] ds = Encoding.ASCII.GetBytes(dd);
c.Send(ds, ds.Length, 0);//发送测试信息
}
richTextBox1.AppendText(recvStr + "\r\n");
richTextBox1.ScrollToCaret(); //c.Disconnect(true);
}
catch (ArgumentNullException a)
{
MessageBox.Show(String.Format("ArgumentNullException:{0}", a));
}
catch (SocketException a)
{
MessageBox.Show(String.Format("SocketException:{0}", a.Message));
}
// MessageBox.Show(String.Format("PressEntertoExit"));
}那个判断服务器返回的值再次发送 好像服务器接收不了啊!!帮看看,谢谢了
try
{
Socket s;
int port = 2000;
string host = "192.168.0.127";
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//创建一个Socket类
s.Bind(ipe);//绑定2000端口
s.Listen(0);//开始监听
//ShowMessage("Waitforconnect");
while (true)
{
Socket temp = s.Accept();//为新建连接创建新的Socket。
//ShowMessage("Getaconnect from " + temp); //this.Invoke(new ShowMes(ShowMessage), "Getaconnect");
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
recvStr = Encoding.ASCII.GetString(recvBytes, 0, bytes);
//ShowMessage(String.Format("ServerGetMessage:{0}", recvStr));//this.Invoke(new ShowMes(ShowMessage), String.Format("ServerGetMessage:{0}", recvStr)); //把客户端传来的信息显示出来
string sendStr = Convert.ToString("nihao");
byte[] bs = Encoding.ASCII.GetBytes (sendStr);
temp.Send(bs, bs.Length, 0);//返回客户端成功信息
}