自從學習編程以來,都是從網上搜索資料,自己成長了許多,突然想着自己的總結或者感悟也放上來呢,就有了這第一篇博文作為開始。
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();
}
}
}
}