解决方案 »
- 关于用C#操作word查找替换数据
- 请问VS 2005里,哪里可以设置IDENTITY_INSERT
- 请问 如何 判断文件的类型啊?
- 请问如何在后台修改前台的一个table的某个单元格中的字体的颜色
- 怎样实现cs与bs之间的通信?up有分
- Mdi子窗体的字体显示为什么那么大?
- 如何把combobox控件 放到toolbar中
- 如何在一个windows services里调用一个activeX控件
- (在线等待) C#中一个简单的问题.(服务器,客户端).....急急急......
- C#程序都有一个Main()函数,但是在.NET中使用C# ,就不需要这个Main()了吗?
- 在C#里绘图时如何将timer加在里面???
- 求教...有会C#反射调用C++的大侠吗?
{
//sendMessage
}
{
public Form1()
{
InitializeComponent();
this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
} //TcpClient newclient = null;
Thread nth = null; Boolean star = true;
//Thread rd = null;
//NetworkStream ns = null;
//BinaryReader nsr = null;
//BinaryWriter nsw = null;
public static IPAddress localaddr = IPAddress.Parse("127.0.0.1"); TcpListener listener = new TcpListener(localaddr, 8888); private void button1_Click(object sender, EventArgs e)
{
listener.Start();
Log("服务器启动");
nth = new Thread(new ThreadStart(clientconnect));
nth.Start();
} private void clientconnect()
{
int count = 1;
while (star)
{
try
{
TcpClient newclient = listener.AcceptTcpClient();
Log( "有" + count + "个客户连接了!");
Thread rd = new Thread(new ParameterizedThreadStart(this.receivedata));
rd.Start(newclient);
count++;
}
catch { } }
} private List<MyClient> tcl = new List<MyClient>();
private void Log(string msg)
{
try
{
listBox1.Items.Add(msg);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
} private void receivedata(object nc)
{ TcpClient newclient = (TcpClient)nc;
NetworkStream ns = newclient.GetStream();
BinaryReader nsr = new BinaryReader(ns);
BinaryWriter nsw = new BinaryWriter(ns);
MyClient c=null;
try
{ c = new MyClient(newclient, nsw);
tcl.Add(c); star = true;
while (newclient.Connected)
{
string str = nsr.ReadString();
OnBroadCastDelegate del = new OnBroadCastDelegate(this.BroadCast);
del.BeginInvoke(newclient, str, null, null); }
}
catch (Exception ex)
{
if (c != null && tcl.Contains(c)) tcl.Remove(c); //System.Diagnostics.Debug.WriteLine(ex.Message);
Log(ex.Message); }
finally
{
nsr.Close();
nsw.Close();
ns.Close();
}
} delegate void OnBroadCastDelegate(TcpClient src, string data); private void BroadCast(TcpClient src, string data)
{
this.listBox1.Items.Add(data); foreach (MyClient mc in tcl)
{
if(mc.Tc==src) continue; mc.Writer.Write(data);
}
} private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//if (ns!=null) ns.Close();
star = false;
tcl.Clear();
listener.Stop();
//newclient.Close();
} class MyClient
{
public MyClient()
{
} public MyClient(TcpClient tc, BinaryWriter w)
{
Tc = tc;
Writer = w;
}
public TcpClient Tc = null;
public BinaryWriter Writer = null;
} }
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;namespace MyChatRoomClient
{
public partial class FChatClient : Form
{
public FChatClient()
{
InitializeComponent();
TextBox.CheckForIllegalCrossThreadCalls = false;
} Thread th = null;
//定义一个接收用的缓冲区(2M字节数组)
byte[] arrMsgRec = new byte[1024 * 1024*2];
Socket SocketClient = null; void ReceiveMsg()
{
while (true)
{
//将接收到的数据存入arrMsgRec数组
int len= SocketClient.Receive(arrMsgRec);
string strMsRec = System.Text.Encoding.UTF8.GetString(arrMsgRec,0,len );
ShowMsg(strMsRec+"\r\n");
}
}
private void btnConnection_Click(object sender, EventArgs e)
{
IPAddress address = IPAddress.Parse(txtIP.Text.Trim());
IPEndPoint endpoint = new IPEndPoint(address, int.Parse(txtPort.Text.Trim()));
SocketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketClient.Connect(endpoint);
th = new Thread(ReceiveMsg);
th.Start();
} void ShowMsg(string msg)
{
txtMessage.AppendText(msg + "/r/n");
}
}
}
服务端:using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.Threading;namespace MyChatRoomServer
{
public partial class FServer : Form
{
public FServer()
{
InitializeComponent();
//关闭微软对文本框的检查
TextBox.CheckForIllegalCrossThreadCalls = false;
} Socket SocketWatch = null;
Dictionary<string, Socket> dict = new Dictionary<string, Socket>();
//Socket socketConnection = null;//负责通信的套接字
/// <summary>
/// 监听客户端请求的方法
/// </summary>
void ServerAccept()
{
//持续不断地监听新德客户端的连接请求
while (true)
{
//一旦监听到客户端请求,就返回一个负责和该客户端通信的套接字socketConnection
Socket socketConnection = SocketWatch.Accept();
listBox1.Items.Add(socketConnection.RemoteEndPoint.ToString());
dict.Add(socketConnection.RemoteEndPoint.ToString(), socketConnection);
ShowMsg("客户端连接成功."+socketConnection .RemoteEndPoint .ToString());
}
}
private void btnBeginListen_Click(object sender, EventArgs e)
{
//创建服务端负责监听的套接字,参数(使用IP4寻址协议,使用流式连接,使用TCP协议传送数据)
SocketWatch=new Socket (AddressFamily .InterNetwork ,SocketType .Stream ,ProtocolType.Tcp );
//获得文本框中IP对象
IPAddress address = IPAddress.Parse(txtIP.Text.Trim());
//创建包含IP和端口的网络节点对象
IPEndPoint endpoint = new IPEndPoint(address,int.Parse ( txtPort.Text.Trim()));
//将负责监听的套接字绑定到一个IP和端口上
SocketWatch.Bind(endpoint );
//设置监听队列长度
SocketWatch.Listen(10);
//开始监听客户端请求,注意:accept方法,会阻断当前的线程
//Socket socketConnection = SocketWatch.Accept();
Thread th = new Thread(ServerAccept);
//设置为后台线程
th.IsBackground=true;
//开启线程
th.Start();
ShowMsg("服务器监听启动成功 ");
} void ShowMsg(string msg)
{
txtMessage.AppendText(msg + "\r\n");
} //发送消息到客户端
private void btnSend_Click(object sender, EventArgs e)
{
string getClient = listBox1.Text;
//拿到文本框内容
string strMsg = txtMsgSend.Text.Trim();
//将要发送的字符串转成utf8对应的字节数组
byte [] arrMsg=System.Text.Encoding.UTF8 .GetBytes(strMsg );
dict[getClient].Send(arrMsg);
// socketConnection.Send(arrMsg);
ShowMsg("发送了数据出去");
}
}
}