server:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace multithreadserv
{
class Threadtcpserver
{
private Socket server;
private int userNum;//在线客户数量
private int socketNum;//连接服务段的数量
private Socket[] socketUser = new Socket[40];//存储在线的客户端

// 将客服端 nowClient 发来的信息 data,发送给其他在线的每个客户端,不包括 nowClient客服端。
private void SendAllUser(byte[] data, Socket nowClient)
{
if (userNum > 0)
{
for (int i = 0; i < socketNum; i++)
{
if (socketUser[i].Equals(nowClient)) continue;

// 在发送过程中可能有些客户已经离线,会发生异常
try
{
socketUser[i].Send(data);
}
catch
{
// 当一个发现异常后,说明 socket[i] 已经离线,需要从socketUser[] 数组中将其删除
Socket temp = socketUser[i];
socketUser[i] = socketUser[socketNum - 1];
i--;
socketNum--;
}
}
}
}

// 客户端 client 的接受信息的方法
private void ReceiveData(object client)
{
Socket nowClient = (Socket)client;
while (true)
{
int res = 0;
byte[] bytes = new byte[1024];
// 不段的接受客户端发来的信息, 当客户端离线后,退出。
try
{
res = nowClient.Receive(bytes);
}
catch
{
// client 离线,更新userNum 值
userNum--;
Console.WriteLine("现在有:{0} 个客户在连接中。", userNum);
return;
}

string str = Encoding.UTF8.GetString(bytes, 0, res);
byte[] data = Encoding.UTF8.GetBytes(str);
//将该信息发送给其他客户端
SendAllUser(data, nowClient);
}
}

// 侦听上线的客户端
private void AccpetUser()
{
while (true)
{
// 当侦听到一个客户端上线后,更新socketUser[],并给此客户端开一个接受信息的线程
Socket nowClient = server.Accept();
socketUser[socketNum++] = nowClient;
userNum++;
Console.WriteLine("现在有:{0} 个客户在连接中。", userNum);

// 开一个线程, 接受 nowClient 发来的信息。
// 这里调用的方法为有参数的方法, 需要使用委托。
Thread nowThread = new Thread(new ParameterizedThreadStart(ReceiveData));
//nowThread.IsBackground = true;
nowThread.Start(nowClient);
}
}

// 构造函数
public Threadtcpserver()
{
userNum = 0;
socketNum = 0;

//初始化 IP 地址
IPAddress local = IPAddress.Parse("192.168.1.101");//客户端的 IPAddress 地址
IPEndPoint iep = new IPEndPoint(local, 3000);// 端口为3000

server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

// 将套接字与本地终结点绑定
server.Bind(iep);

//在本地 3000 端口行上进行监听
server.Listen(20);

Console.WriteLine("等待客户级进行连接...");
AccpetUser();
}
static void Main(string[] args)
{
Threadtcpserver instance = new Threadtcpserver();
}
}

}

Client:

using System;
using System.Collections.Generic;
using System.Text;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace multithreadclient
{
class ClientSocket
{
// public string names;
public Socket client;
public ClientSocket()
{
client = null;
}
public void ReceiveData()
{
byte[] data = new byte[1024];
while (true)
{
int res = 0;
try
{
res = client.Receive(data);
}
catch
{
Console.WriteLine("与服务器断开连接!");
return;
}

Console.WriteLine(Encoding.UTF8.GetString(data, 0, res));
Console.WriteLine();
}
}
static void Main(string[] args)
{

//byte[] buf = new byte[1024];

ClientSocket ads = new ClientSocket();

IPAddress local = IPAddress.Parse("192.168.1.101");// 服务器的 IPAddres 地址
IPEndPoint iep = new IPEndPoint(local, 3000);
try
{
ads.client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ads.client.Connect(iep);
}
catch (SocketException)
{
Console.WriteLine("无法连接到服务器");
Console.ReadLine();
return;
}
finally
{
}

Console.Write("连接成功, 请输入昵称:");
string names = Console.ReadLine();

Thread newThread = new Thread(new ThreadStart(ads.ReceiveData));
newThread.Start();

names += " 说:";
while (true)
{
// 在控制台上输入一条消息
//Console.WriteLine("我想说:");
Console.WriteLine();
string input = Console.ReadLine();
input = names + input;
ads.client.Send(Encoding.UTF8.GetBytes(input));
}
Console.WriteLine("断开与服务器的连接...");
ads.client.Close();
Console.ReadLine();
}
}
}

server and client的更多相关文章

  1. TCP连接的状态与关闭方式及其对Server与Client的影响

    TCP连接的状态与关闭方式及其对Server与Client的影响 1. TCP连接的状态 首先介绍一下TCP连接建立与关闭过程中的状态.TCP连接过程是状态的转换,促使状态发生转换的因素包括用户调用. ...

  2. navicat 连接sqlserver提示要安装 sql server native client

    navicat 连接sqlserver提示要安装 sql server native client 解决方法:其实navicat自带sqlncli_x64.msi,就在安装目录下,安装后问题解决!

  3. C Socket Programming for Linux with a Server and Client Example Code

    Typically two processes communicate with each other on a single system through one of the following ...

  4. Netty4.0学习笔记系列之一:Server与Client的通讯

    http://blog.csdn.net/u013252773/article/details/21046697 本文是学习Netty的第一篇文章,主要对Netty的Server和Client间的通讯 ...

  5. 浅谈Android系统进程间通信(IPC)机制Binder中的Server和Client获得Service Manager接口之路

    文章转载至CSDN社区罗升阳的安卓之旅,原文地址:http://blog.csdn.net/luoshengyang/article/details/6627260 在前面一篇文章浅谈Service ...

  6. 基于winsocket的框体Server和Client

    前面学了一点Winsock的知识,会编写简单的Server和Client,现在就想通过VS2008编写框体的Server和Client,而不是在控制台上的操作了,毕竟学编程就是要多加练习,在实践中发现 ...

  7. Winsock网络编程笔记(3)----基于UDP的server和client

    在上一篇随笔中,对Winsock中基于tcp面向连接的Server和Client通信进行了说明,但是,Winsock中,Server和Client间还可以通过无连接通信,也就是采用UDP协议.. 因此 ...

  8. Winsock网络编程笔记(2)----基于TCP的server和client

    今天抽空看了一些简单的东西,主要是对服务器server和客户端client的简单实现. 面向连接的server和client,其工作流程如下图所示: 服务器和客户端将按照这个流程就行开发..(个人觉得 ...

  9. Feign报错Caused by: com.netflix.client.ClientException: Load balancer does not have available server for client

    问题描述 使用Feign调用微服务接口报错,如下: java.lang.RuntimeException: com.netflix.client.ClientException: Load balan ...

  10. JVM的Server与Client运行模式区别与切换

    概述 JVM有两种运行模式Server与Client.两种模式的区别在于,Client模式启动速度较快,Server模式启动较慢:但是启动进入稳定期长期运行之后Server模式的程序运行速度比Clie ...

随机推荐

  1. HTML 5 应用程序缓存(上)

    什么是应用程序缓存(Application Cache)?HTML5 引入了应用程序缓存,这意味着 web 应用可进行缓存,并可在没有因特网连接时进行访问. 应用程序缓存为应用带来三个优势: 离线浏览 ...

  2. python 学习笔记十五 django基础

    Python的WEB框架有Django.Tornado.Flask 等多种,Django相较与其他WEB框架其优势为:大而全,框架本身集成了ORM.模型绑定.模板引擎.缓存.Session等诸多功能. ...

  3. [翻译]lithium介绍

    什么是li3? 首创框架 li3 是第一个并且是唯一一个从PHP 5.3+建立起来的相当出色的php框架,而且破天荒的第一次引入全新技术,包括通过一组唯一,统一的api(接口)在关系型(relatio ...

  4. oracle 锁表问题

    oracle执行表数据更新的时候,会遇到锁表问题,比方说,会遇到这样的问题,主要原因是这张表被其他人占用,修改数据没有提交.oracle为了避免脏数据的产生,在其安全机制下,锁住该表. 执行如下操作, ...

  5. linux开发缩写

    1.CONFIG_OF 在一些驱动中经常看到#ifdef CONFIG_OF,这里的OF是Open Firmware. Open Firmware. This was invented long ti ...

  6. 最全面的常用正则表达式大全 zz

    很多不太懂正则的朋友,在遇到需要用正则校验数据时,往往是在网上去找很久,结果找来的还是不很符合要求.所以我最近把开发中常用的一些正则表达式整理了一下,包括校验数字.字符.一些特殊的需求等等.给自己留个 ...

  7. dsp28377控制DM9000收发数据

    首先感谢上一篇转载文章的作者给出的参考,下面是一些自己在调试过程中的一些步骤: 首先把代码贴上来: //------------------------------------------------ ...

  8. html局部打印

    html页面局部打印的小栗子 只要修改点击打印的按钮和打印的div区域的id就行啦 <!DOCTYPE html> <html> <head> <title& ...

  9. MySQL中的两种临时表

    MySQL中的两种临时表 伯乐在线2016-07-06 05:16:52阅读(4556)评论(3) 声明:本文由入驻搜狐公众平台的作者撰写,除搜狐官方账号外,观点仅代表作者本人,不代表搜狐立场.举报 ...

  10. struts2值栈内部数据结构详解

    值栈是struts2内部一片很重要的区域,我在初学的时候,发现对于值栈这个数据结构的理解不是很深刻.例如OGNLContext是什么,ActionContext和值栈有什么关系.为什么ActionCo ...