using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace test4_2
{
public partial class Form1 : Form
{
Socket connectSocket;
//Socket client;
byte[] bytes = new byte[1024];
delegate void listboxDel(string s);
listboxDel listboxdel;
public Form1()
{
InitializeComponent();
textBoxContent.Focus();
listboxdel = new listboxDel(listbox);
//為串連指派線程
Thread threadConnect = new Thread(new ThreadStart(Connect));
threadConnect.Start();
}
public void listbox(string str)
{
listBox1.Items.Add(str);
listBox1.SelectedIndex = listBox1.Items.Count - 1;
listBox1.ClearSelected();
}
//串連方法
public void Connect()
{
try
{
//建立串連socket
connectSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//開始非同步串連
connectSocket.BeginConnect(IPAddress.Parse("172.16.94.152"),
82,
new AsyncCallback(ConnectCallback), //定義回呼函數代理
connectSocket); //傳遞給回呼函數的狀態
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
//串連方法的回呼函數
private void ConnectCallback(IAsyncResult ar)
{
try
{
//從傳遞的狀態中擷取通訊端,建立一個用戶端通訊端
Socket client = (Socket)ar.AsyncState;
//完成掛起的串連操作
client.EndConnect(ar);
listBox1.Invoke(listboxdel, "串連伺服器成功,可以開始通話!");
client.BeginReceive(bytes, 0, 1000, 0, new AsyncCallback(receivecallback), client);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public void receivecallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
int length = client.EndReceive(ar);
listBox1.Invoke(listboxdel, Encoding.UTF8.GetString(bytes, 0, length));
client.BeginReceive(bytes, 0, 1000, 0, new AsyncCallback(receivecallback), client);
}
catch
{
}
}
//發送方法
private void Send(String data)
{
//使用ASCII轉換字串為位元組序列
byte[] byteData = Encoding.UTF8.GetBytes(data); //將字串轉換成位元組序列
//開始向遠端裝置發送資料
connectSocket.BeginSend(byteData, 0, byteData.Length, SocketFlags.None,
new AsyncCallback(SendCallback), connectSocket);
}
//發送方法的回呼函數
private void SendCallback(IAsyncResult ar)
{
try
{
//從傳遞的狀態中擷取通訊端,建立一個用戶端通訊端
Socket client = (Socket)ar.AsyncState;
//結束非同步資料轉送操作,返回傳輸的位元組數
int bytesSent = client.EndSend(ar);
listBox1.Invoke(listboxdel, textBoxUser.Text +":"+ textBoxContent.Text);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
private void buttonSend_Click(object sender, EventArgs e)
{
Send(textBoxUser.Text+":"+textBoxContent.Text);
}
}
}