一、实验要求
具体要求包括:
1,Server支持多客户访问;
2,C与S之间使用TCP连接;
3,C与C之间直接通信(不是通过S传递)。
4,C与C之间直接通信既可以使用TCP,也可以使用UDP。
5,可以使用Socket,也可以使用TcpClient/UdpClient等;
6,实验示意图如下:
二、实验思路
(1)客户端登陆服务端时,打开客户端的监听并发送客户端的用户名和端口号。
(2)客户端发送信息时,服务端根据客户端的用户名返回端口号。
(3)客户端根据服务端返回的端口号与信息接收方进行tcp通信。
(4)客户端与客户端通信时,不保留连接,仅在需要发送信息时建立连接。
三、应用界面
(1)服务器界面:
(2)客户端界面(未登录):
(3)客户端界面(登陆):
(4)客户端与客户端互相通信:
(5)客户端给多个客户端发送消息:
(6)客户端退出:
源码如下:
ClientForm.cs:
using System;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using System.Text;
namespace Client
{
public partial class ClientForm : Form
{
public ClientForm()
{
InitializeComponent();
UserNameList = new List
();
UserPortList = new List
();
isMessageCome = false;
this.label_State.Text = "未检测到服务器";
this.FormClosing += ClientWindow_Closing;
}
private bool isMessageCome { get; set; }
private bool isLogin { get; set; }
private TcpListener listener;
private TcpClient SocketForClient;
private BinaryReader br_C;
private BinaryWriter bw_C;
private string receiveString;
private List
UserNameList { get; set; }
private List
UserPortList { get; set; }
private TcpClient client_S;
private NetworkStream networkStream_S;
private BinaryReader br_S;
private BinaryWriter bw_S;
private IPAddress localIpAddress;
private int remotePort;
private string remoteHost;
private string userName { get; set; }
private string userPort { get; set; }
private enum clientState
{
Login,
Talk,
Logout
};
private delegate void Delegate1();
private delegate void Delegate2();
private void ClientWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (client_S != null)
{
SendMessageToServer(clientState.Logout, "退出服务器。", textBox_Port.Text);
br_S.Close();
bw_S.Close();
client_S.Close();
}
}
private voi