using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace 聊天室服务端2
{
class Program
{
List<Socket> socketList = new List<Socket>();
static void Main(string[] args)
{
Socket mainServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
int pose = 3001;
IPAddress ip = IPAddress.Parse("192.168.1.104");
EndPoint point = new IPEndPoint(ip, pose);
mainServer.Bind(point);
mainServer.Listen(10);
Console.WriteLine("服务器启动成功,等待连接...");
Socket ClientVIP = mainServer.Accept();
Console.WriteLine("连接成功");
IPEndPoint ClientVIPip = (IPEndPoint)ClientVIP.RemoteEndPoint;
Console.WriteLine("客户端地址{0},端口{1}", ClientVIPip.Address, ClientVIPip.Port);
ReceiveAndSend RS = new ReceiveAndSend(ClientVIP);
RS.Se();
RS.Re();
Console.ReadKey();
}
}
class ReceiveAndSend
{
private Socket socketObj;
private Thread tse,tre;
public ReceiveAndSend(Socket s)
{
socketObj = s;
tse = new Thread(Se);
tse.Start();
tre = new Thread(Re);
tre.Start();
}
public void Se()
{
while (true)
{
string sendStr = "服务器:"+Console.ReadLine();
byte[] sendData = Encoding.Default.GetBytes(sendStr);
socketObj.Send(sendData);//发送
}
}
public void Re()
{
while (true)
{
byte[] recData = new byte[1024];
int length = socketObj.Receive(recData);//读取
string recStr = Encoding.Default.GetString(recData, 0, length);
Console.WriteLine(recStr);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace 聊天室客户端2
{
class Program
{
static void Main(string[] args)
{
Socket mainClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
int pose = 3001;
IPAddress ip = IPAddress.Parse("192.168.1.104");
EndPoint point = new IPEndPoint(ip, pose);
mainClient.Connect(point);
ReceiveAndSend RS = new ReceiveAndSend(mainClient);
RS.Re();
RS.Se();
Console.ReadKey();
}
}
class ReceiveAndSend
{
private Socket socketObj;
private Thread tse, tre;
public ReceiveAndSend(Socket s)
{
socketObj = s;
tse = new Thread(Se);
tse.Start();
tre = new Thread(Re);
tre.Start();
}
public void Se()
{
while (true)
{
string sendStr = "客户端:" + Console.ReadLine();
byte[] sendData = Encoding.Default.GetBytes(sendStr);
socketObj.Send(sendData);//发送
}
}
public void Re()
{
while (true)
{
byte[] recData = new byte[1024];
int length = socketObj.Receive(recData);//读取
string recStr = Encoding.Default.GetString(recData, 0, length);
Console.WriteLine(recStr);
}
}
}
}