public Socket c;
public int bytes;
public byte[] recvBytes = new byte[1024];
public string recvStr = "";
private void button1_Click(object sender, EventArgs e)
{
try
{
int port = 2001;
string host = "192.168.1.1";
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);
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"));
}
C#中用Socket网络编程的问题,从客户端把数据发送到指定的IP和端口
最新推荐文章于 2023-11-15 18:57:26 发布
本文介绍了一个使用C#编写的简单Socket客户端程序示例,该客户端能够连接到指定的服务器并发送测试消息,同时接收并显示服务器返回的信息。
1万+

被折叠的 条评论
为什么被折叠?



