服务端:
using System;using System.IO;using System.Collections;using System.Collections.Generic;using System.Configuration;using System.Data.SqlClient;using System.Text.RegularExpressions;using MyLibrary;using System.ComponentModel;using System.Text;using System.Security.Cryptography;using Microsoft.International.Converters.PinYinConverter;using System.Reflection;using System.Net;using System.Net.Sockets;using System.Threading;namespace first_project{ static class Program { static Dictionary clientList = new Dictionary(); static void Main(string[] args) { Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); serverSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 99)); Console.WriteLine("listening..."); serverSocket.Listen(10); while (true) { Socket socketCommu = serverSocket.Accept(); clientList.Add(socketCommu.RemoteEndPoint.ToString().Split(':')[1], socketCommu); Console.WriteLine(socketCommu.RemoteEndPoint + ": connected"); Thread threadReceive = new Thread(Receive); threadReceive.IsBackground = true; threadReceive.Start(socketCommu); Thread threadSend = new Thread(Send); threadSend.IsBackground = true; threadSend.Start(); } } static void Receive(object obj) { byte[] buffer; Socket socketCommu = obj as Socket; while (true) { buffer = new byte[3 * 1024 * 1024]; int r = socketCommu.Receive(buffer); if(r == 0) break; Console.WriteLine(socketCommu.RemoteEndPoint + ": " + Encoding.UTF8.GetString(buffer, 0, r)); } } static void Send() { Console.WriteLine("input client port:"); string port = Console.ReadLine(); Socket socketCommu = clientList[port]; while (true) socketCommu.Send(Encoding.UTF8.GetBytes(Console.ReadLine())); } }}客户端:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Net.Sockets;using System.Net;using System.Threading;namespace client{ class Program { static Socket clientSocket; static void Main(string[] args) { clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); clientSocket.Connect(IPAddress.Parse("127.0.0.1"), 99); Console.WriteLine("server connected"); Thread th = new Thread(Send); th.IsBackground = true; th.Start(); byte[] buffer; while(true) { buffer = new byte[3 * 1024 * 1024]; int r = clientSocket.Receive(buffer); if(r == 0) break; Console.WriteLine(clientSocket.RemoteEndPoint +": "+Encoding.UTF8.GetString(buffer, 0, r)); } } static void Send() { while(true) clientSocket.Send(Encoding.UTF8.GetBytes(Console.ReadLine())); } }}为什么输入已经连接的客户端端口抛异常提示字典clientList的键不存在? |