110,500
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;
namespace Chenyun_UDP_Server
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string strIP = textBox1.Text.Trim();
int port = Int32.Parse(textBox2.Text.Trim());
IPAddress ip = IPAddress.Parse(strIP);
IPEndPoint hostEP = new IPEndPoint(ip, port);
//创建Socket实例
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//尝试连接
try
{
socket.Connect(hostEP);
}
catch (Exception se)
{
MessageBox.Show("连接错误" + se.Message, "提示信息", MessageBoxButtons.RetryCancel, MessageBoxIcon.Information);
}
//发送给远程主机的请求内容串
string sendStr = "BD6AED";
//创建bytes字节数组以转换发送串
byte[] bytesSendStr = new byte[1024];
//将发送内容字符串转换成字节byte数组
bytesSendStr = Encoding.ASCII.GetBytes(sendStr);
try
{
//向主机发送请求
socket.Send(bytesSendStr, bytesSendStr.Length, 0);
}
catch (Exception ce)
{
MessageBox.Show("发送错误:" + ce.Message, "提示信息", MessageBoxButtons.RetryCancel, MessageBoxIcon.Information);
}
//声明接收返回内容的字符串
string recvStr = "";
//声明字节数组,一次接收数据的长度为1024字节
byte[] recvBytes = new byte[1024];
//返回实际接受内同的字节数
int bytes = 0;
//循环读取
while (true)
{
bytes = socket.Receive(recvBytes, recvBytes.Length, 0);
//读完后退出循环
if (bytes <= 0)
break;
//将读取的字节数专号为字符串
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
}
//将所有读取的字符串转换为字节数组
byte[] content = Encoding.ASCII.GetBytes(recvStr);
try
{
//创建文件流实例
FileStream fs = new FileStream("c:\\ceshishuju.txt", FileMode.OpenOrCreate, FileAccess.Write);
//写入文件
fs.Write(content, 0, content.Length);
}
catch (Exception fe)
{
MessageBox.Show("文件创建/写入错误:" + fe.Message, "提示信息", MessageBoxButtons.RetryCancel, MessageBoxIcon.Information);
}
//禁用Socket
socket.Shutdown(SocketShutdown.Both);
//关闭它
socket.Close();
}
}
}