Socket 通讯,一个简单的 C/S 聊天小程序

  Socket,这玩意,当时不会的时候,抄别人的都用不好,简单的一句话形容就是“笨死了”;也是很多人写的太复杂,不容易理解造成的。最近在搞erlang和C的通讯,也想试试erlang是不是可以和C#简单通讯,就简单的做了些测试用例,比较简单,觉得新手也可以接受。

  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Drawing;
  6 using System.Linq;
  7 using System.Text;
  8 using System.Windows.Forms;
  9 using System.Net.Sockets;
 10 using System.Net;
 11 using System.Threading;
 12
 13 namespace ChatClient
 14 {
 15     public partial class Form1 : Form
 16     {
 17         private System.Windows.Forms.RichTextBox richTextBox1;
 18         private System.Windows.Forms.TextBox textBox1;
 19         private System.ComponentModel.IContainer components = null;
 20
 21         /// <summary>
 22         /// 服务端侦听端口
 23         /// </summary>
 24         private const int _serverPort = 8707;
 25         /// <summary>
 26         /// 客户端侦听端口
 27         /// </summary>
 28         private const int _clientPort = 8708;
 29         /// <summary>
 30         /// 缓存大小
 31         /// </summary>
 32         private const int _bufferSize = 1024;
 33         /// <summary>
 34         /// 服务器IP
 35         /// </summary>
 36         private const string ServerIP = "172.17.47.199";  //手动修改为指定服务器ip
 37
 38         private Thread thread;
 39
 40         private void Form1_Load(object sender, EventArgs e)
 41         {
 42             thread = new Thread(new ThreadStart(delegate { Listenning(); }));
 43             thread.Start();
 44         }
 45
 46         void textBox_KeyUp(object sender, KeyEventArgs e)
 47         {
 48             if (e.KeyCode == Keys.Enter)
 49             {
 50                 string msg;
 51                 if ((msg = textBox1.Text.Trim()).Length > 0)
 52                 {
 53                     SendMessage(msg);
 54                 }
 55                 textBox1.Clear();
 56             }
 57         }
 58
 59         void SendMessage(string msg)
 60         {
 61             try
 62             {
 63                 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 64                 IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ServerIP), _serverPort);
 65                 socket.Connect(endPoint);
 66                 byte[] buffer = System.Text.ASCIIEncoding.UTF8.GetBytes(msg);
 67                 socket.Send(buffer);
 68                 socket.Close();
 69             }
 70             catch
 71             { }
 72         }
 73
 74         void Listenning()
 75         {
 76             TcpListener listener = new TcpListener(_clientPort);
 77             listener.Start();
 78             while (true)
 79             {
 80                 Socket socket = listener.AcceptSocket();
 81                 byte[] buffer = new byte[_bufferSize];
 82                 socket.Receive(buffer);
 83                 int lastNullIndex = _bufferSize - 1;
 84                 while (true)
 85                 {
 86                     if (buffer[lastNullIndex] != ‘\0‘)
 87                         break;
 88                     lastNullIndex--;
 89                 }
 90                 string msg = Encoding.UTF8.GetString(buffer, 0, lastNullIndex + 1);
 91                 WriteLine(msg);
 92                 socket.Close();
 93             }
 94         }
 95
 96         void WriteLine(string msg)
 97         {
 98             this.Invoke(new MethodInvoker(delegate
 99             {
100                 this.richTextBox1.AppendText(msg + Environment.NewLine);
101             }));
102         }
103
104         public Form1()
105         {
106             this.richTextBox1 = new System.Windows.Forms.RichTextBox();
107             this.textBox1 = new System.Windows.Forms.TextBox();
108             this.SuspendLayout();
109             //
110             // richTextBox1
111             //
112             this.richTextBox1.Location = new System.Drawing.Point(1, 2);
113             this.richTextBox1.Name = "richTextBox1";
114             this.richTextBox1.Size = new System.Drawing.Size(282, 188);
115             this.richTextBox1.TabIndex = 3;
116             this.richTextBox1.Text = "";
117             this.richTextBox1.KeyUp += new System.Windows.Forms.KeyEventHandler(this.textBox_KeyUp);
118             //
119             // textBox1
120             //
121             this.textBox1.Location = new System.Drawing.Point(3, 196);
122             this.textBox1.Multiline = true;
123             this.textBox1.Name = "textBox1";
124             this.textBox1.Size = new System.Drawing.Size(277, 65);
125             this.textBox1.TabIndex = 2;
126             this.textBox1.KeyUp += new System.Windows.Forms.KeyEventHandler(this.textBox_KeyUp);
127             //
128             // Form1
129             //
130             this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
131             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
132             this.ClientSize = new System.Drawing.Size(284, 262);
133             this.Controls.Add(this.richTextBox1);
134             this.Controls.Add(this.textBox1);
135             this.Name = "Form1";
136             this.Text = "Form1";
137             this.Load += new System.EventHandler(this.Form1_Load);
138             this.ResumeLayout(false);
139             this.PerformLayout();
140         }
141
142         protected override void Dispose(bool disposing)
143         {
144             if (disposing && (components != null))
145             {
146                 components.Dispose();
147             }
148             base.Dispose(disposing);
149         }
150     }
151 }

Client端

  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Data;
  5 using System.Diagnostics;
  6 using System.Linq;
  7 using System.ServiceProcess;
  8 using System.Text;
  9 using System.Net;
 10 using System.Net.Sockets;
 11 using System.Collections;
 12
 13 namespace ChatService
 14 {
 15     public partial class Service1 : ServiceBase
 16     {
 17         /// <summary>
 18         /// 服务端侦听端口
 19         /// </summary>
 20         private const int _serverPort = 8707;
 21         /// <summary>
 22         /// 客户端侦听端口
 23         /// </summary>
 24         private const int _clientPort = 8708;
 25         /// <summary>
 26         /// 缓存大小
 27         /// </summary>
 28         private const int _bufferSize = 1024;
 29         /// <summary>
 30         /// 服务器IP
 31         /// </summary>
 32         private const string ServerIP = "172.17.47.199";  //手动修改为指定服务器ip
 33         /// <summary>
 34         /// 客户端IP
 35         /// </summary>
 36         //private Hashtable ServerIPs = new Hashtable();  //存放ip + port
 37         private List<string> ServerIPs = new List<string>();
 38
 39         public Service1()
 40         {
 41             //InitializeComponent();   //从控制台改为服务,需要注释下面的一行,打开本行
 42             Listenning();
 43         }
 44
 45         void SendMessage(string msg)
 46         {
 47
 48             for (int i = ServerIPs.Count - 1; i >= 0; i--)
 49             {
 50                 try
 51                 {
 52                     Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 53                     IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ServerIPs[i]), _clientPort);
 54                     socket.Connect(endPoint);
 55                     byte[] buffer = System.Text.ASCIIEncoding.UTF8.GetBytes((ServerIPs[i] + " say: " + msg).Trim());
 56                     socket.Send(buffer);
 57                     socket.Close();
 58                 }
 59                 catch
 60                 {
 61                     ServerIPs.RemoveAt(i);
 62                 }
 63             }
 64         }
 65
 66         void Listenning()
 67         {
 68
 69             TcpListener listener = new TcpListener(_serverPort);
 70             listener.Start();
 71             while (true)
 72             {
 73                 Socket socket = listener.AcceptSocket();
 74                 var s = socket.RemoteEndPoint.ToString();
 75                 var ipstr = s.Substring(0, s.IndexOf(":"));
 76
 77                 if (!ServerIPs.Contains(ipstr))
 78                 {
 79                     ServerIPs.Add(ipstr);
 80                 }
 81
 82                 byte[] buffer = new byte[_bufferSize];
 83                 socket.Receive(buffer);
 84                 int lastNullIndex = _bufferSize - 1;
 85
 86                 while (true)
 87                 {
 88                     if (buffer[lastNullIndex] != ‘\0‘)
 89                         break;
 90                     lastNullIndex--;
 91                 }
 92                 string msg = Encoding.UTF8.GetString(buffer, 0, lastNullIndex + 1);
 93                 SendMessage(msg);
 94                 Console.WriteLine(msg);//服务模式下关闭
 95             }
 96         }
 97
 98         protected override void OnStart(string[] args)
 99         {
100             Listenning();
101         }
102
103         protected override void OnStop()
104         {
105
106         }
107     }
108 }

Server端

逻辑视图(比较简单):

1.左上角的是一个远程客户端,右上角是本地客户端,右下角是本地服务端(暂时改为控制台程序)

2.这段程序只给不懂得如何用socket玩玩

3.这里面剔除了数据加密、异步获取等繁杂的过程,想要学习可以参照:http://yunpan.cn/cKT2ZHdKRMILz  访问密码 b610

时间: 2024-10-10 18:09:44

Socket 通讯,一个简单的 C/S 聊天小程序的相关文章

一个简单的计算分数的小程序

一个简单的计算分数的小程序 代码如下: package Day05; public class ExamGradeDemo { public static void main(String[] args) { char[][] answers = { {'C','B','D','C','A','A','D','C','D','C'}, {'A','C','B','D','C','A','D','C','B','D'}, {'A','C','B','D','B','D','C','A','A','

go语言实现一个简单的登录注册web小程序

最近学习golang也有一段时间了,基础差不多学了个大概,因为本人是java程序员,所以对web更感兴趣.根据<go web编程>中的例子改编一个更简单的例子,供新手参考,废话不多说,上菜: 这个例子使用到了beego框架和beedb框架,如果是go新手beego和beedb得自己去google下载安装. 目录结构: index.go package controllers import ( "fmt" "github.com/astaxie/beego"

一个简单的加减乘除自动生成小程序升级版(JAVA)

1 import java.util.Scanner; 2 public class Suan { 3 public static void main(String[] args) { 4 int []b;//设置数组来存放随机产生数 5 b=new int [4]; 6 Scanner in=new Scanner(System.in); 7 System.out.println("请选择你想练习的题型:"); 8 System.out.println(" 1.分数的加减乘

利用java的Socket实现一个简单hello/hi聊天程序

利用java的Socket实现一个简单hello/hi聊天程序 首先,我们来用java实现一个简单的hello/hi聊天程序.在这个程序里,我学习到了怎么用socket套接套接字来进行编程.简单理解了一些关于socket套接字和底层调用的关系.关于java的封装思想,我学会了一些东西,java里真的是万物皆对象.还学到了一点多线程的知识. TCP 在这里,不得不先介绍以下TCP.TCP是传输层面向连接的协议.提供了端到端的进程之间的通信方式.TCP在通信之前要先建立连接.这里我们称这个建立连接的

Socket编程,简单的类似qq聊天,可以两台电脑互通

原文:Socket编程,简单的类似qq聊天,可以两台电脑互通 源代码下载地址:http://www.zuidaima.com/share/1550463676648448.htm Socket编程,简单的类似qq聊天,可以两台电脑互通,刚学习网络编程的可以看下 源码截图:

用Python socket实现一个简单的http服务器(post 与get 的区别)

预备知识: 关于http协议的基础请参考这里. 关于socket基础函数请参考这里. 关于python网络编程基础请参考这里. 废话不多说,前面实现过使用linux c 或者python 充当客户端来获取http 响应,也利用muduo库实现过一个简易http服务器,现在来实现一个python版的简易http服务器,代码改编自http://www.cnblogs.com/vamei/ httpServer.py Python Code 1 2 3 4 5 6 7 8 9 10 11 12 13

Netty学习——基于netty实现简单的客户端聊天小程序

Netty学习——基于netty实现简单的客户端聊天小程序 效果图,聊天程序展示 (TCP编程实现) 后端代码: package com.dawa.netty.chatexample; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEven

[软件测试学习]考虑到测试的代码编写/int.parse的非法输入—由一个简单的c#闰年检测程序说起

一个简单的C#的闰年检测程序 1.闰年检测的函数编写 当提起检测平年闰年时候,第一反应写出的代码 1 public static bool isLeapYear(int year){ 2 return ((year % 4 == 0 && year % 100 != 0)||(year % 400 == 0)) 3 } 但是这个并不易于测试和出现错后的修改,更改代码如下 1 public static bool isLeapYear(int year){ 2 bool check = ne

Spring学习(二)——使用用Gradle构建一个简单的Spring MVC Web应用程序

1.新建一个Gradle工程(Project) 在新建工程窗口的左侧中选择 [Gradle],右侧保持默认选择,点击next,模块命名为VelocityDemo. 2.在该工程下新建一个 module,在弹出的窗口的左侧中选择 [Gradle],右侧勾选[Spring MVC],如下图所示: 并勾选[Application server],下方选择框中选择Tomcat7.0,如无该选项,则选中右边的 [ New... ] -- [ Tomcat Server ], 配置 Tomcat .配置好后