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 入门级客户端与服务端交互代码 网 ...
随机推荐
- 实验二 合作:王宏财 http://www.cnblogs.com/wanghongcai/
package 四则运算; import javax.swing.JFrame; import javax.swing.JButton; import javax.swing.JOptionPane; ...
- 广商博客冲刺第二天new
队名:雷锋队 队员:叶子鹏 王佳宁 张奇聪 张振演 曾柏树 项目:广商博客(嵌入APP) 执笔人:王佳宁 第一天沖刺傳送門 第三天沖刺傳送門 今天主要是写需求分析,在经过组员的热烈地讨论,需求分析如下 ...
- APP推广(预期方案)
首先,在推广过程中有一些定的弊端:我们这个O2O平台暂时只能适用于学校局域网. 因为我们的APP才刚刚“出炉”不久,在网络上还是属于一篇空白的状态,我们想过可以在百度百科上进行相应的推广,如果有用户搜 ...
- beta 答辩总结
评审表 编号 团队名称 项目名称 格式 内容 PPT 演讲 答辩 总分/100 1 天机组 指尖加密 14 13 13 13 13 66 2 PMS Your eyes 14 14 17 14 15 ...
- [2017BUAA软件工程]第0次作业
第一部分:结缘计算机 1. 你为什么选择计算机专业?你认为你的条件如何?和这些博主比呢?(必答) 选择计算机专业的一个重要原因是因为计算机专业的就业前景好,由于计算机本身具有的各种优点,现在几乎所有的 ...
- wamp升级php5.3.10到5.4.31版本
wamp升级php5.3.10到5.4.31版本 1. 停止WAMP服务器. 2. 去网站windows.php.net 下载php-5.4.31-nts-Win32-VC9-x86.zip. 不 ...
- 学习 已经登录windows的情况下获取windows的密码
官网 http://blog.gentilkiwi.com/mimikatz 下载地点 https://github.com/gentilkiwi/mimikatz/releases/latest 使 ...
- Jquery :animate反复执行的动画可以利用函数的回调
<html><head><script type="text/javascript" src="/jquery/jquery.js" ...
- Centos6.5下VNC Server配置
整个流程如下~ 1.首先,检查下本机是否安装了vnc: 提示没有安装,那么开始装吧: 2.先关闭防火墙 查看防火墙状态: 关闭防火墙: 注:要切到root下 [carsonzhu@localhost ...
- pandas缺失值处理
1.检查缺失值 为了更容易地检测缺失值(以及跨越不同的数组dtype),Pandas提供了isnull()和notnull()函数,它们也是Series和DataFrame对象的方法 - 示例1 im ...