socket服务端和客户端通讯简单例子
2012-11-13 09:59
387 查看
/*client*/ public partial class FormClient : Form { public FormClient() { InitializeComponent(); } private void btnSend_Click(object sender, EventArgs e) { Client client = new Client(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8500)); lblMsg.Text = "服务器IP及端口:" + client.socket.RemoteEndPoint.ToString(); try { //发送消息 client.Send(tbMsg.Text); listBox1.Items.Add(string.Format("{0}发送信息:{1}", client.socket.LocalEndPoint, tbMsg.Text)); //接收 string recvMsg = client.Receive(); listBox1.Items.Add(recvMsg); listBox1.Items.Add(""); } finally { client.Close(); } } public class Client { private const int buffer = 1024; public Socket socket; public Client(IPEndPoint iep) { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(iep); } public string Receive() { byte[] data = new byte[buffer]; int recv = socket.Receive(data); return Encoding.UTF8.GetString(data, 0, recv); } public void SendFile(string fileName) { socket.SendFile(fileName); } public void Send(string msg) { byte[] data = Encoding.UTF8.GetBytes(msg); socket.Send(data); } public void Close() { socket.Shutdown(SocketShutdown.Both); socket.Close(); } } } /*server*/ public partial class FormService : Form { public FormService() { InitializeComponent(); Thread serThread = new Thread(new ThreadStart(Listen)); serThread.Start(); } private void Listen() { const int buffer = 10240; IPAddress ip = IPAddress.Parse("127.0.0.1"); IPEndPoint iep = new IPEndPoint(ip, 8500); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Bind(iep); byte[] cliData = new byte[buffer]; socket.Listen(10); lblMsg.Text = string.Format("开始在{0}{1}上监听", iep.Address.ToString(), iep.Port.ToString()); Socket client; int recv; while (true) { client = socket.Accept(); recv = client.Receive(cliData); //接收消息 string cliMsg = Encoding.UTF8.GetString(cliData, 0, recv); cliMsg = DateTime.Now.ToShortTimeString() + "," + client.RemoteEndPoint.ToString() + "发来信息:" + cliMsg; this.listBox1.Items.Add(cliMsg); string serMsg = "服务器返回信息:OK."; byte[] serByte = Encoding.UTF8.GetBytes(serMsg); client.Send(serByte); } } private void FormService_FormClosing(object sender, FormClosingEventArgs e) { Process.GetCurrentProcess().Kill(); } }
相关文章推荐
- node.js服务端和QT客户端简单Socket通讯
- JAVA 服务端和客户端Socket通信的简单例子
- 最简单的socket客户端与服务端例子
- 关于Socket的客户端服务端的简单例子“本机回射” 4000
- 一个简单的socket客户端和服务端的例子
- 基于Socket简单的客户端-服务端例子
- 一个简单的socket客户端和服务端的例子
- PHP基于socket实现的简单客户端和服务端通讯功能示例
- (C#:Socket)简单的服务端与客户端通信。
- windows的socket_tcp服务端与linux的socket_tcp客服端简单通讯
- C# Socket简单例子(服务器与客户端通信)
- Socket通讯-C#客户端与Java服务端通讯(发送消息和文件)
- 一个最简单的SOAP客户端与服务端测试实例(主要是该例子一个类中写了多个方法)
- C# Socket TCP简单例子(服务器与客户端通信)
- 简单的Socket 编程 服务端和客户端 (封装)
- 用Socket实现的简单客户端和服务端程序(一)
- C# Socket简单例子(服务器与客户端通信)
- 使用socket实现简单的客户端和服务端通信(C#语言)
- 【socket编程】一个简单的基于UDP的客户/服务端例子(vs2008)
- 用Socket实现的简单客户端和服务端程序(二)