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

namespace Socket客户端
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Socket socketSend;//负责通信的Socket
///


/// 连接服务器按钮
///

///
///
private void btn_Cont_Click(object sender, EventArgs e)
{
try
{
//创建负责通信的Socket
socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//获取远程要连接的服务器的IP地址以及端口号
IPAddress ipaddress = IPAddress.Parse(textIP.Text);//可以将一个字符串的IP地址转化为IPaddress的对象
EndPoint point = new IPEndPoint(ipaddress, Convert.ToInt32(textPort.Text));//(ip地址,字符转端口号方法)
//连接服务器
socketSend.Connect(point);
ShowMsg("连接成功");
//开启一个子线程接收服务器发来的消息
Thread th = new Thread(Receive);
th.IsBackground = true;
th.Start();
}catch
{ }

    }
    /// <summary>
    /// 不停接收服务器发来的消息
    /// </summary>
    private void Receive()
    {
        try
        {
            while (true)
            {
                byte[] buffer = new byte[1023 * 1023 * 2];
                int r = socketSend.Receive(buffer);
                if (r == 0)
                    break;
                string str = Encoding.UTF8.GetString(buffer, 0, r);
                ShowMsg(socketSend.RemoteEndPoint + ":" + str);

            }
        }
        catch
        { }
    }

    private void ShowMsg(string str)
    {
        textLog.AppendText(str + "\r\n");
    }

    /// <summary>
    /// 客户端向服务器发送消息
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void btn_Send_Click(object sender, EventArgs e)
    {
        string str = textMsg.Text.Trim();
        byte[] date = Encoding.UTF8.GetBytes(str);
        socketSend.Send(date);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Control.CheckForIllegalCrossThreadCalls = false;
    }
}

}