服务端:

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;
using System.IO; namespace 服务端
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false;
} /// <summary>
/// 监听socket
/// </summary>
Socket socketListen; Dictionary<string, Socket> dirSocket = new Dictionary<string, Socket>(); //户务端监听客户端连接情况
private void btnListen_Click(object sender, EventArgs e)
{
try
{
socketListen = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ip = IPAddress.Any; IPEndPoint point = new IPEndPoint(ip, Int32.Parse(txtPort.Text)); socketListen.Bind(point); socketListen.Listen(); showMsg("监听成功"); Thread thread = new Thread(Listen); thread.IsBackground = true; thread.Start();
}
catch (Exception)
{ } } /// <summary>
/// 监听客服端
/// </summary>
void Listen()
{ try
{
//不断的监听客户端
while (true)
{
Socket socket = socketListen.Accept(); showMsg(socket.RemoteEndPoint.ToString() + ":连接成功"); cbList.Items.Add(socket.RemoteEndPoint.ToString()); dirSocket.Add(socket.RemoteEndPoint.ToString(), socket); //不断接受客户端信息
Thread thread = new Thread(Receive); thread.IsBackground = true; thread.Start(socket); } }
catch (Exception)
{ } }
/// <summary>
/// 接收客服端的信息
/// </summary>
/// <param name="o"></param>
void Receive(object o)
{
try
{
Socket socketSend = o as Socket;
byte[] buffer = new byte[ * * ]; while (true)
{
int r = socketSend.Receive(buffer); if (r <= )
{
break;
} string result = Encoding.UTF8.GetString(buffer, , r); showMsg(socketSend.RemoteEndPoint.ToString() + ":" + result); }
}
catch (Exception)
{ } } /// <summary>
/// 显示信息
/// </summary>
/// <param name="msg"></param>
void showMsg(string msg)
{
txtLog.AppendText(msg + "\r\n");
} /// <summary>
/// 发送信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSendMsg_Click(object sender, EventArgs e)
{
string ipAddress = cbList.SelectedItem.ToString(); if (string.IsNullOrEmpty(ipAddress))
{
return;
} string msg = this.txtMsg.Text.Trim(); byte[] msgBytes = Encoding.UTF8.GetBytes(msg); byte[] newArray = GetByteArray(,msgBytes); dirSocket[ipAddress].Send(newArray); } /// <summary>
/// 选择文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSelectFile_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
this.txtPath.Text = ofd.FileName;
} } /// <summary>
/// 发送文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSendFile_Click(object sender, EventArgs e)
{
string ipAddress = cbList.SelectedItem.ToString(); if (string.IsNullOrEmpty(ipAddress))
{
return;
} string filename = this.txtPath.Text.Trim(); byte[] msgBytes = File.ReadAllBytes(filename); byte[] newArray = GetByteArray(, msgBytes); dirSocket[ipAddress].Send(newArray);
} /// <summary>
/// 发送抖屏
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnMoveScreen_Click(object sender, EventArgs e)
{
string ipAddress = cbList.SelectedItem.ToString(); if (string.IsNullOrEmpty(ipAddress))
{
return;
} byte[] newArray = new byte[] { }; dirSocket[ipAddress].Send(newArray);
} /// <summary>
/// 处理发送byte数据
/// </summary>
/// <param name="type"></param>
/// <param name="array"></param>
/// <returns></returns>
private byte[] GetByteArray(int type,byte[] array)
{
byte[] newArray = new byte[array.Length+]; array.CopyTo(newArray, ); switch (type)
{
case :
newArray[] = ;
break;
case :
newArray[] = ;
break;
default:
newArray[] = ;
break;
} return newArray;
} }
}

客服端:

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;
using System.IO; namespace 客户端
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false;
} Socket socket; private void btnListen_Click(object sender, EventArgs e)
{
try
{ socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ip = IPAddress.Parse(txtAddress.Text); IPEndPoint point = new IPEndPoint(ip, Int32.Parse(txtPort.Text)); socket.Connect(point); showMsg("连接服务端成功!!!!"); Thread thread = new Thread(Receive); thread.IsBackground = true; thread.SetApartmentState(ApartmentState.STA); thread.Start();
}
catch (Exception ex)
{ }
} void Receive()
{
try
{ byte[] buffer = new byte[ * * ]; while (true)
{ int r = socket.Receive(buffer);
if (r <= ) break; switch (buffer[])
{
case : //文本内容
GetMsg(buffer, r);
break;
case : //文本文件
GetFile(buffer, r);
break; default: //抖屏
GetMoveScreen();
break;
} }
}
catch (Exception)
{ }
} /// <summary>
/// 接收内容
/// </summary>
/// <param name="array"></param>
/// <param name="realLength"></param>
void GetMsg(byte[] array,int realLength)
{
string msg = Encoding.UTF8.GetString(array, , realLength-); showMsg(msg);
}
/// <summary>
/// 接收文件
/// </summary>
/// <param name="array"></param>
/// <param name="realLength"></param>
void GetFile(byte[] array,int realLength)
{
SaveFileDialog sfd = new SaveFileDialog(); if (sfd.ShowDialog() == DialogResult.OK)
{
string filename = sfd.FileName; using(FileStream fs = new FileStream(filename,FileMode.Create,FileAccess.ReadWrite))
{
fs.Write(array, , realLength - );
} showMsg("文件保存到:"+filename+"成功!!!");
}
}
Random r = new Random();
/// <summary>
/// 抖屏
/// </summary>
void GetMoveScreen()
{
Point startPoint = this.Location; for (int i = ; i < ; i++)
{
this.Location = new Point(startPoint.X + r.Next(), startPoint.Y + r.Next());
} this.Location = startPoint;
} /// <summary>
/// 显示内容
/// </summary>
/// <param name="p"></param>
private void showMsg(string p)
{
textBox1.AppendText(p + "\r\n");
} /// <summary>
/// 发送内容
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSend_Click(object sender, EventArgs e)
{
try
{
string msg = txtMsg.Text.Trim(); byte[] buffer = Encoding.UTF8.GetBytes(msg); socket.Send(buffer);
}
catch (Exception)
{ }
} }
}

socket 聊天室的更多相关文章

  1. Java Socket聊天室编程(二)之利用socket实现单聊聊天室

    这篇文章主要介绍了Java Socket聊天室编程(二)之利用socket实现单聊聊天室的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下 在上篇文章Java Socket聊天室编程(一)之 ...

  2. Java Socket聊天室编程(一)之利用socket实现聊天之消息推送

    这篇文章主要介绍了Java Socket聊天室编程(一)之利用socket实现聊天之消息推送的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下 网上已经有很多利用socket实现聊天的例子了 ...

  3. python socket 聊天室

    socket 发送的时候,使用的是全双工的形式,不是半双工的形式.全双工就是类似于电话,可以一直通信.并且,在发送后,如果又接受数据,那么在这个接受到数据之前,整个过程是不会停止的.会进行堵塞,堵塞就 ...

  4. TCP/IP以及Socket聊天室带类库源码分享

    TCP/IP以及Socket聊天室带类库源码分享 最近遇到个设备,需要去和客户的软件做一个网络通信交互,一般的我们的上位机都是作为客户端来和设备通信的,这次要作为服务端来监听客户端,在这个背景下,我查 ...

  5. html5 WebSocket 与 PHP socket 聊天室原理

    html js <!DOCTYPE html> <html lang="en"> <head> <meta charset="U ...

  6. 基于Spring 4.0 的 Web Socket 聊天室/游戏服务端简单架构

    在现在很多业务场景(比如聊天室),又或者是手机端的一些online游戏,都需要做到实时通信,那怎么来进行双向通信呢,总不见得用曾经很破旧的ajax每隔10秒或者每隔20秒来请求吧,我的天呐(),这尼玛 ...

  7. Python socket聊天室程序

    http://blog.csdn.net/calling_wisdom/article/details/42524745 今天用python的socket模块实现了一个聊天室的程序 虽然功能比较简单, ...

  8. 【Unity3D自学记录】Unity3D网络之Socket聊天室初探

    首先创建一个服务端程序,这个程序就用VS的控制台程序做即可了. 代码例如以下: using System; using System.Collections.Generic; using System ...

  9. Socket聊天室-TcpListener,TcpClient

    参考自:http://blog.csdn.net/liguo9860/article/details/6148614 服务端:

  10. socket聊天室(服务端)(多线程)(TCP)

    #include<string.h> #include<signal.h> #include<stdio.h> #include<sys/socket.h&g ...

随机推荐

  1. Java微信二次开发(五)

    消息加密 需要到入库:commons-io-2.4.jar,commons-codec-1.9.jar(在官网的Java微信加密demo下) 第一步:访问https://mp.weixin.qq.co ...

  2. mysql 启动和关闭外键约束

    在MySQL中删除一张表或一条数据的时候,出现 [Err] 1451 -Cannot delete or update a parent row: a foreign key constraint f ...

  3. Django-website 程序案例系列-12 CSRF

    django为用户实现防止跨站请求伪造的功能 需要配置settings.py:  django.middleware.csrf.CsrfViewMiddleware 1. form表单提交 <f ...

  4. codeforces 798 D. Mike and distribution

    D. Mike and distribution time limit per test 2 seconds memory limit per test 256 megabytes input sta ...

  5. 【POI每日题解 #8】DYN-Dynamite

    你问蒟蒻为什么一天写两篇每日题解? 难道每日坚果你不能一天吃两包吗? 题目链接 哇…这道题第一反应就是二分答案[太明显了 枚举答案 就那个“关键节点到这些点中距离的最小值的最大值”[蒟蒻读了好几遍…… ...

  6. 【刷题】UOJ #374 【ZJOI2018】历史

    九条可怜是一个热爱阅读的女孩子. 这段时间,她看了一本非常有趣的小说,这本小说的架空世界引起了她的兴趣. 这个世界有 \(n\) 个城市,这 \(n\) 个城市被恰好 \(n-1\) 条双向道路联通, ...

  7. Python的栈和队列实现

    栈 class Node: def __init__(self, data=None): self.next = None self.data = data class Stack: def __in ...

  8. Learn Python The Hard Way, 2nd Edition

    看完了这本书,你决定继续做编程.也许它能成为你的一个职业,也许它能成为你的一项爱好.但你需要一些指导,确保自己不会走错了道路,或帮助你从这个新业余爱好中得到最大的乐趣. 我做了很久的编程.久的你都想象 ...

  9. [POI2012]BON-Vouchers----你敢模拟吗?

    链接:https://www.luogu.org/problemnew/show/P3536 题意: 定义n个数为幸运数字,一共有n批人,设第i批人有x个,则它们会依次取走余下的x的倍数中最小的x个, ...

  10. mapping生成sam文件时出现[mem_sam_pe] paired reads have different names错误

    用以下命令修复: bbrename.sh in1=read1.fq in2=read2.fq out1=renamed1.fq out2=renamed2.fq bbrename.sh 下载地址网上自 ...