C# Socket编程(一)

自从学习编程以来,都是从网上搜索资料,自己成长了许多,突然想着自己的总结或者感悟也放上来呢,就有了这第一篇博文作为开始。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;

namespace SocketTest
{
   public partial class Form1 : Form
{
String SocketIP = "127.0.0.1";
int SocketPort = 6000;
static Socket ClientSocket;
public Form1()
{
   InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
ClientSocket.Send(Encoding.ASCII.GetBytes(textBox1.Text.ToString().Trim()));
}

private void Form1_Load(object sender, EventArgs e)
{
try
{
IPAddress ip = IPAddress.Parse(SocketIP); //将IP地址字符串转换成IPAddress实例
ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//使用指定的地址簇协议、套接字类型和通信协议
IPEndPoint endPoint = new IPEndPoint(ip, SocketPort); // 用指定的ip和端口号初始化IPEndPoint实例
ClientSocket.Connect(endPoint); //与远程主机建立连接

textBox2.Text = "开始发送消息";

byte[] message = Encoding.ASCII.GetBytes("Connect the Server"); //通信时实际发送的是字节数组,所以要将发送消息转换字节
ClientSocket.Send(message);
textBox2.Text = textBox2.Text + "\\n" + "发送消息为:" + Encoding.ASCII.GetString(message);

//byte[] receive = new byte[1024];
//int length = ClientSocket.Receive(receive); // length 接收字节数组长度
//Console.WriteLine("接收消息为:" + Encoding.ASCII.GetString(receive));
//ClientSocket.Close(); //关闭连接
}
catch (Exception ex)
{
textBox2.Text = ex.Message.ToString();
}
}
}
}

猜你喜欢

转载自www.cnblogs.com/merfhey/p/11345094.html
今日推荐