这是服务器端:
public partial class MainForm : Form
{
int Port = 8000;
//创建监听对象
TcpListener listener = null;
//定义一个委托
delegate void SetSaft(string text);
ArrayList conList = new ArrayList();
//确定编码
Encoding UTF8 = Encoding.UTF8;
Encoding GB2312 = Encoding.GetEncoding("GB2312");
//创建线程
Thread ListerThread = null;
Thread DataThread = null;
public MainForm()
{
InitializeComponent();
}
/// <summary>
/// 处理连接线程
/// </summary>
public void AccetptRequest()
{
try
{
while (true)
{
//确定是否挂起连接请求
if (listener.Pending())
{
//建立连接
Socket s = listener.AcceptSocket();
//添加到当前连接的列表
conList.Add(s);
if (s.Connected)
{
string serverEndpoint = "欢迎登录服务器:"+s.LocalEndPoint.ToString();
byte[] bgb = GB2312.GetBytes(serverEndpoint);
byte[] buffer = Encoding.Convert(GB2312, UTF8, bgb);
//发送给客户端
s.Send(buffer);
//获取远端终点
string rpoint = s.RemoteEndPoint.ToString();
//将客户端信息加在列表中
AddList(rpoint);
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Thread.Sleep(1000);
}
public void ReceiveData()
{
while (true)
{
try
{
ArrayList closeSocketList = new ArrayList();
closeSocketList.Clear();
//循环每一个已经建立的连接
foreach (Socket s in conList)
{
NetworkStream ns = new NetworkStream(s);
System.IO.StreamReader reader = new System.IO.StreamReader(ns);
//表示独到是否有可用的数据
if (ns.DataAvailable)
{
//从当前流中获取一行字符
string result = reader.ReadLine();
byte[] u = UTF8.GetBytes(result);
byte[] gb = Encoding.Convert(UTF8, GB2312, u);
//取得转化为Gb2312编码的字符串
string sgb = GB2312.GetString(gb);
if (sgb.StartsWith("Closing"))
{
//将当前连接添加关闭连接
closeSocketList.Add(s);
}
}
reader.Close();
ns.Close();
}
foreach (Socket s in closeSocketList)
{
DelList(s.RemoteEndPoint.ToString());
s.Close();
conList.Remove(s);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void AddList(object text)
{
//判断对方控件是否调用了invoke方法
if (this.listBox1.InvokeRequired)
{
SetSaft d = new SetSaft(AddList);
this.Invoke(d, new object[] { text });
}
else
{
this.listBox1.Items.Add(text);
}
}
private void DelList(object text)
{
if (this.listBox1.InvokeRequired)
{
SetSaft d = new SetSaft(DelList);
this.Invoke(d, new object[] { text });
}
else
{
this.listBox1.Items.Remove(text);
}
}
private void 开始服务ToolStripMenuItem_Click(object sender, EventArgs e)
{
//初始话指定的侦听的端口
listener = new TcpListener(Port);
listener.Start();
//启动连接线程
ListerThread=new Thread(new ThreadStart( AccetptRequest));
//启动接受数据线程
ListerThread.Start();
DataThread=new Thread( new ThreadStart(ReceiveData));
DataThread.Start();
}
private void MainForm_Load(object sender, EventArgs e)
{
//UserInfo();
}
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
//Bll.User.Operate operater = new Bll.User.Operate();
//operater.Exit(loginForm.NAME, loginForm.PASSWORD);
//Application.Exit();
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
foreach (Socket o in conList)
{
o.Close();
}
ListerThread.Abort();
DataThread.Abort();
}
catch(SocketException ex)
{
MessageBox.Show(ex.Message);
}
}
}
下面是客户端:
public partial class MainForm : Form
{
Socket client = null;
public string IP = null;//表示要连接的服务器IP
private int Port = 8000;
System.Threading.Thread data = null;
Encoding UF8 = Encoding.UTF8;
Encoding GB2312 = Encoding.GetEncoding("GB2312");
delegate void SetSafe(string text);
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint end = new IPEndPoint(IPAddress.Parse("192.168.253.195"), Port);
try
{
client.Connect(end);
byte[] buffer = new byte[1024];
PonySocket.Helper helper = new PonySocket.Helper(client, buffer);
client.BeginReceive(buffer,0,buffer.Length,SocketFlags.None,new AsyncCallback(Receive),helper);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void Receive(IAsyncResult ar)
{
PonySocket.Helper h = ar.AsyncState as PonySocket.Helper;
int c= client.EndReceive(ar);
//递归的接受数据
h.ChatSocket.BeginReceive(h.MsgByte, 0, h.MsgByte.Length, SocketFlags.None, new AsyncCallback(Receive), h);
this.label1.Text = Encoding.GetEncoding("gb2312").GetString(h.MsgByte, 0, c);
}
private void btnConnecting_Click(object sender, EventArgs e)
{
//Promp promp = new Promp();
//promp.ShowDialog();
//IP = promp.IP;
//try
//{
// client = new Socket(AddressFamily.InterNetwork,
// SocketType.Stream,
// ProtocolType.Tcp);
// client.Connect(IP, Port);
// string sendString = client.LocalEndPoint.ToString()+"成功连接";
// //将连接信息发送给服务器端
// byte[] buffer = UF8.GetBytes(sendString);
// client.Send(buffer);
// data = new System.Threading.Thread(new ThreadStart(DataStart));
// data.Start();
//}
//catch (SocketException ex)
//{
// MessageBox.Show(ex.Message);
//}
}
private void DataStart()
{
while (true)
{
try
{
NetworkStream ns = new NetworkStream(client);
System.IO.StreamReader reader = new System.IO.StreamReader(ns);
string result = reader.ReadLine();
byte[] u = UF8.GetBytes(result);
byte[] sgb = Encoding.Convert(UF8, GB2312, u);
string strgb = GB2312.GetString(sgb);
this.label1.Text = strgb;
ns.Close();
reader.Close();
}
catch (SocketException ex)
{
MessageBox.Show(ex.Message);
}
Thread.Sleep(1000);
}
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
data.Abort();
Byte[] buffer = UF8.GetBytes("Closing"+client.LocalEndPoint.AddressFamily.ToString());
client.Send(buffer);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
客户端用了两中方法实现,可是出现问题是服务器可以取得客户端的连接信息(IP和端口号)但是双方实现不了通信