保證可用
TCP 客户端与服务端 相互发消息
UDP 客户端之间通信
public partial class Form1 : Form
{
private IPAddress serverIP;
private IPEndPoint serverFullAddr;//完整终端地址
private Socket sock;
private Thread myThread = null;
public Form1()
{
InitializeComponent();
btnClose.Enabled = false;
}
private void btnConn_Click(object sender, EventArgs e)
{
serverIP = IPAddress.Parse(tbxIP.Text);
try
{
serverFullAddr = new IPEndPoint(serverIP, int.Parse(tbxPort.Text));//设置IP,端口
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(serverFullAddr);
btnConn.Enabled = false;
lblError.Text = "连接成功";
btnClose.Enabled = true;
myThread = new Thread(new ThreadStart(Listen));
myThread.Start();
}
catch (Exception ee)
{
lblError.Text = "连接失败" ee;
}
}
private void btnClose_Click(object sender, EventArgs e)
{
sock.Close();
btnConn.Enabled = true;
}
private void btnSend_Click(object sender, EventArgs e)
{
byte[] byteSend = System.Text.Encoding.Default.GetBytes(this.tbxMessage.Text);
try
{
sock.Send(byteSend);
}
catch (Exception ex)
{
lblError.Text = "发送错误" ex;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Listen()
{
byte[] message = new byte[1024];
string mess = "";
while (true)
{
int bytes = sock.Receive(message);
mess = Encoding.Default.GetString(message, 0, bytes);
Invoke(new PrintRecvMssgDelegate(PrintRecvMssg), new object[] { mess });
}
}
private delegate void PrintRecvMssgDelegate(string s);
private void PrintRecvMssg(string info)
{
reciveTxt.Text = string.Format("{0}\r\n",info);
}
private void btnCLR2_Click(object sender, EventArgs e)
{
reciveTxt.Text = "";
}
private void btnCLR_Click(object sender, EventArgs e)
{
tbxMessage.Text = "";
}
private void CloseForm(object sender, FormClosedEventArgs e)
{
System.Diagnostics.Process.GetCurrentProcess().Kill(); //关闭窗口后关闭后台进程
}
}
}
评论