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 入门级客户端与服务端交互代码 网 ...
随机推荐
- 第三个spring冲刺第8天
今天,我们忙于完成精美的背景,还有难度的具体设置,如何达到最理想化,为此我们今天主要是做了开会讨论,但还没有完全确定好结论,明天就应该能做出结论,然后修改后台的难度设置了.
- PHP 闭包获取外部变量和global关键字声明变量的区别
最近在学习workerman的时候比较频繁的接触到回调函数,使用中经常会因为worker的使用方式不同,会用这两种不同的方式去调用外部的worker变量,这里就整理一下PHP闭包获取外部变量和glob ...
- 牛客OI周赛7-提高组
https://ac.nowcoder.com/acm/contest/371#question A.小睿睿的等式 #include <bits/stdc++.h> using names ...
- [转载]Memory Limits for Windows and Windows Server Releases
Memory Limits for Windows and Windows Server Releases This topic describes the memory limits for sup ...
- 使用 SSH 秘钥远程连接
团队开发中常用到 Git.SVN 等版本控制工具,可以大大提高开发效率. 就是将代码统一放到一个代码仓库中,方便管理. 为了安全起见,每次push.pull 代码的时候,都需要输入用户名.密码, 对于 ...
- matplotlib之scatter自动绘制散点
# 使用matplotlib.pyplot.scatter绘制散点 import matplotlib.pyplot as plt from pylab import mpl # 设置默认字体,解决中 ...
- 关于jQuery.when()用法的调研
1.该方法在jQuery1.5开始被引入. 2.用法测试 a.var url1 = "/resource/ar/hometab/index_tab_games.json", ...
- pgm15
这部分我们讨论结构学习,也就是 graph 的边我们并不清楚.很自然我们可以用 fully observed 数据来做,但是也可能碰到有 missing data 的情况.一般来说前者是比较常见的.就 ...
- Popular Cows POJ - 2186(强连通分量)
Every cow's dream is to become the most popular cow in the herd. In a herd of N (1 <= N <= 10, ...
- Linux 下 wordpress 无法安装插件
修改目录权限mkdir -p wp-content/tmpchown -R www:www wp-contentchmod -R 777 wp-content 配置修改wp-config.php搜索 ...