TCP的代码
视频已经发布,这里是所有的代码仅供参考.
TCP服务器:
MainWindow里面的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading; namespace TCPServerExample
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
TcpListener myListener;
List<User> userList = new List<User>();
bool isExit;
IPAddress ip;
public MainWindow()
{
InitializeComponent();
button1.IsEnabled = true;
button2.IsEnabled = false;
}
//开始按钮
private void button1_Click(object sender, RoutedEventArgs e)
{
button1.IsEnabled = false;
button2.IsEnabled = true;
isExit = true;
//获取本机IP地址
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
foreach (var item in ips)
{
if (item.AddressFamily==AddressFamily.InterNetwork)
{
ip = item;
break;
}
} myListener = new TcpListener(ip, );
IPEndPoint iep = new IPEndPoint(ip, );
myListener.Start();
//textBlock1.Text += string.Format("服务器在{0}的{1}打开监听",ips[5],port);
textBlock1.Text += string.Format("服务器在{0}打开监听\n", iep);
Thread t1 = new Thread(ListenClientConnect);
t1.Start();
} //第一步,开启监听
private void ListenClientConnect()
{
//获取相应客户端套接字
while (isExit)
{
try
{
TcpClient newClient = myListener.AcceptTcpClient();
User user = new User(newClient);
userList.Add(user);
Action act = delegate()
{
textBlock1.Text += string.Format("用户{0}连接成功,当前在线用户数为{1}\n",
newClient.Client.RemoteEndPoint, userList.Count);
};
textBlock1.Dispatcher.Invoke(act);
Thread t2 = new Thread(ReceiveMessage);
t2.Start(user);
}
catch
{
break;
} }
}
//第二步,接收消息
private void ReceiveMessage(Object user1)
{
User newuser = (User)user1;
while (isExit)
{
try
{
string message = newuser.br.ReadString();
AddMessage(string.Format("客户端:{0}发送信息:{1}\n",
newuser.client.Client.RemoteEndPoint, message));
string[] array = message.Split(',');
switch (array[])
{
case "Login":
{
newuser.username = array[];
//服务器告诉所有在线客户端,有新的用户登录
for (int i = ; i < userList.Count; i++)
{
if (userList[i].username != newuser.username)
{
userList[i].bw.Write("Login," + array[]);
}
newuser.bw.Write("Login," + userList[i].username);
}
break;
}
case "Logout":
{
for (int i = ; i < userList.Count; i++)
{
if (userList[i].username != newuser.username)
{
userList[i].bw.Write("Logout," + array[]);
}
}
userList.Remove(newuser);
AddMessage("客户端" + newuser.username + "退出," + "当前用户数为:" + userList.Count);
return;
}
case "Talk":
{
string target = array[];
for (int i = ; i < userList.Count; i++)
{
if (userList[i].username == target)
{
userList[i].bw.Write("Talk," + newuser.username + "," + array[]);
}
}
break;
}
default:
{
MessageBox.Show("什么意思?");
break;
}
}
}
catch
{
break;
}
}
}
//第三步,添加消息到textBlock
private void AddMessage(string message)
{
Action act = delegate()
{
textBlock1.Text += message;
};
textBlock1.Dispatcher.Invoke(act);
} //结束按钮
private void button2_Click(object sender, RoutedEventArgs e)
{
button1.IsEnabled = true;
button2.IsEnabled = false;
for (int i = ; i < userList.Count; i++)
{
try
{
userList[i].bw.Write("服务器已停止监听!");
}
catch
{
break;
}
userList[i].Close();
}
isExit = false;
Thread.Sleep();
myListener.Stop(); for (int i = ; i < userList.Count; i++)
{
userList[i].Close();
}
textBlock1.Text += "监听结束!";
}
}
}
User类的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO; namespace TCPServerExample
{
class User
{
public string username{get;set;}
public TcpClient client{get;set;}
public BinaryWriter bw { get; set; }
public BinaryReader br { get; set; }
public User(TcpClient newclient)
{
this.client = newclient;
NetworkStream networkstream = newclient.GetStream();
bw = new BinaryWriter(networkstream);
br = new BinaryReader(networkstream); } public void Close()
{
client.Close();
bw.Close();
br.Close(); }
}
}
TCP客户端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading; namespace TCPClientExample
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
TcpClient newClient;
BinaryWriter bw;
BinaryReader br;
string username;
//enum item { listBox1, textBox1 };
//enum opreation { add,remove};
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
button1.IsEnabled = false;
username = textBox2.Text;
//创建套接字(TcpClient对象)
newClient = new TcpClient();
//获取服务器IP地址
IPAddress ip = IPAddress.Parse("10.0.2.15");
try
{
newClient.Connect(ip, );
listBox1.Items.Add("连接成功!");
}
catch
{
listBox1.Items.Add("连接失败!");
button1.IsEnabled = true;
return;
}
NetworkStream networkStream = newClient.GetStream();
bw = new BinaryWriter(networkStream);
br = new BinaryReader(networkStream);
bw.Write("Login," + username);
Thread t1 = new Thread(ReceiveMessage);
t1.Start();
}
//第一步,接收消息
private void ReceiveMessage()
{
string message = "";
while (true)
{
try
{
message = br.ReadString();
}
catch
{
break;
}
string[] array = message.Split(',');
switch (array[])
{
case "Login":
AddUser(array[]);
break;
case "Logout":
RemoveUser(array[]);
break;
case "Talk":
AddMessage(array[] + ":" + array[]);
break;
default:
AddMessage(message);
break;
}
}
}
//第二步,添加消息到textBlock
private void AddMessage(string message)
{
Action act = delegate()
{
listBox1.Items.Add(message);
};
listBox2.Dispatcher.Invoke(act);
}
//第三步,添加用户到列表
private void AddUser(string name)
{
Action act = delegate()
{
listBox2.Items.Add(name);
};
listBox2.Dispatcher.Invoke(act);
}
//第四步,移除用户
private void RemoveUser(string name)
{
Action act = delegate()
{
listBox2.Items.Remove(name);
};
listBox2.Dispatcher.Invoke(act);
} private void button2_Click(object sender, RoutedEventArgs e)
{
NetworkStream networkStream = newClient.GetStream();
bw = new BinaryWriter(networkStream);
string message = textBox1.Text;
bw.Write("Talk,"+listBox2.SelectedItem+","+message);
listBox1.Items.Add(username + ":" + textBox1.Text);
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
try
{
bw.Write("Logout," + username);
}
catch
{
MessageBox.Show("与服务器连接失败!");
}
bw.Close();
}
}
}
我这里的ip都是我自己电脑的ip,你们参考别忘了改ip
我是蜀云泉,我爱许嵩.吼吼~
TCP的代码的更多相关文章
- 网络基础 二 (TCP协议代码,UDP协议代码)
TCP 三次握手,四次断开 三次握手(必须先由客户端发起) 客户端:发送请求帧给服务器. 服务器:收到客户端的请求,并回复可以建立连接 客户端:与服务器建立连接 四次断开 (谁先发起都行,以客户端为 ...
- 一些tcp通讯代码
1,nginx-lua 需要设置nginx配置文件 resolver 223.5.5.5 223.6.6.6; lua_package_path "/usr/local/nginx/conf ...
- tcp cubic代码分析
/* * TCP CUBIC: Binary Increase Congestion control for TCP v2.3 * Home page: * http://netsrv.csc.ncs ...
- 【Jmeter源码解读】003——TCP采样器代码解析
采样器地址为src.protocol.tcp.sampler 1.结构图 还有两个文件 ReadException:响应的异常,举例子就是服务端发生读取文本的问题,会产生异常 TCPSampler:采 ...
- TCP通讯代码
服务端代码: import socket server_socket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) # 使用固定端口 server_ ...
- TCP template 代码
服务端 from socket import * server= socket(AF_INET,SOCK_STREAM) server.bind(('127.0.0.1',8080)) server. ...
- TCP服务器/客户端代码示例
TCP服务器代码: #include <errno.h> #include <string.h> #include <stdlib.h> #include < ...
- TCP和UDP Client 代码
最近学习要求做网络编程,使用从网上找了一些资料,主要是网络协议的分层等通讯,你可以查看英文版的资料:CScharp网络编程英文版 下面直接给出代码吧,我想一看应该就懂. TCP Client 代码: ...
- c++ 网络编程(一)TCP/UDP windows/linux 下入门级socket通信 客户端与服务端交互代码
原文作者:aircraft 原文地址:https://www.cnblogs.com/DOMLX/p/9601511.html c++ 网络编程(一)TCP/UDP 入门级客户端与服务端交互代码 网 ...
随机推荐
- github链接
github链接:https://github.com/bjing123 test1:https://github.com/bjing123/test-/blob/master/test1.t ...
- [日常工作]GS使用消息队列进行凭证实时记账 提高性能配置方法
1. 安装消息队列服务 使用平台技术部的一键安装工具,安装. 自带jdk以及activeMQ 自动注册服务. 比较方便. 2. 修改/gsp/config下面的MQ配置文件,将消息队列服务修改为当前虚 ...
- 如何根据元素的className获取元素?
getElementsByClassName()是HTML5 新增的DOM API.IE8以下不支持 我们知道,原生的方法,是getElementById()和getElementsByTagName ...
- 关于python 自带csv库的使用心得 附带操作实例以及excel下乱码的解决
因为上次帮我们产品处理过一个文件,他想生成能excel处理操作的.但是上次由于时间非常紧张,所以并没有处理好. 正好无聊就来好好研究一下 ,找算法要了几个 csv文件.来好好玩一玩. 全篇使用了pyt ...
- liunx速查
文件和目录 Linux 主要目录速查表 /:根目录,一般根目录下只存放目录,在 linux 下有且只有一个根目录,所有的东西都是从这里开始 当在终端里输入 /home,其实是在告诉电脑,先从 /(根目 ...
- BZOJ1001 BJOI2006狼抓兔子(最小割+最短路)
显然答案就是最小割.直接跑dinic也能过,不过显得不太靠谱. 考虑更正确的做法.作为一个平面图,如果要把他割成两半,那么显然可以用一条曲线覆盖且仅覆盖所有割边.于是我们把空白区域看成点,隔开他们的边 ...
- Redis之发布订阅
一 什么是发布订阅 发布订阅模式又叫观察者模式,它定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖它的对象都将得到通知 Redis 发布订阅(pub/sub)是一种消息通信模式: ...
- 【POI每日题解 #7】TES-Intelligence Test
题目链接 这道题第一眼看去类比BANK-Cash Dispenser 不过1e6 * 1e6 = 1e12 分分钟MLE啊 想到优化 就yy到一种近似主席树的做法 来维护类似BANK的一堆序列 开 ...
- Leetcode 1.两数之和 By Python
思路 很容易想到的方法是二重循环遍历一遍,但是会很慢 把加法变减法可以大大加速 代码 class Solution: def twoSum(self, nums, target): "&qu ...
- 自学Linux Shell4.2-监测磁盘空间mount umount df du
点击返回 自学Linux命令行与Shell脚本之路 4.2-监测磁盘空间mount umount df du 1. 挂载存储媒体mount 移除存储媒体umount ls命令用于显示文件目录列表, ...