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 简易服务端 {
class Program {
static void Main(string[] args) {
//声明服务端的socket
showMsg("开启服务器....");
Socket service = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipPoint = new IPEndPoint(IPAddress.Any, 50816);
service.Bind(ipPoint);
service.Listen(10);
Thread th = new Thread(accept);
showMsg("等待用户连接.....");
th.Start(service);
}
//等待连接的好友
static void accept(object obj) {
Socket acceptService = obj as Socket;
while (true) {
Console.WriteLine("===========");
acceptService.Accept();
Thread th = new Thread(receive);
th.Start(acceptService);
}
}
//接受客户端的消息
static void receive(object obj) {
Socket receiveService = obj as Socket;
while (true) {
byte[] by = new byte[1024 * 1024];
Console.WriteLine("=====接受到了-======");
int a = 0;
IPEndPoint ipP = new IPEndPoint(IPAddress.Parse("192.168.16.178"),50816);
EndPoint p=ipP;
a = receiveService.ReceiveFrom(by,ref p);
Console.WriteLine("=====接受到了======" + a);
if (a == 0) break;
showMsg(receiveService.RemoteEndPoint + "发来消息: " + Encoding.UTF8.GetString(by));
}
}
//将内容显示到消息框当中
static void showMsg(string str) {
Console.WriteLine(str+"\n");
}
}
}
------------------------------------------------------------------------------
客户端代码
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 简易服务端 {
class Program {
static void Main(string[] args) {
//声明服务端的socket
showMsg("开启服务器....");
Socket service = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipPoint = new IPEndPoint(IPAddress.Any, 50816);
service.Bind(ipPoint);
service.Listen(10);
Thread th = new Thread(accept);
showMsg("等待用户连接.....");
th.Start(service);
}
//等待连接的好友
static void accept(object obj) {
Socket acceptService = obj as Socket;
while (true) {
Console.WriteLine("===========");
acceptService.Accept();
Thread th = new Thread(receive);
th.Start(acceptService);
}
}
//接受客户端的消息
static void receive(object obj) {
Socket receiveService = obj as Socket;
while (true) {
byte[] by = new byte[1024 * 1024];
Console.WriteLine("=====接受到了-======");
int a = 0;
IPEndPoint ipP = new IPEndPoint(IPAddress.Parse("192.168.16.178"),50816);
EndPoint p=ipP;
a = receiveService.ReceiveFrom(by,ref p);
Console.WriteLine("=====接受到了======" + a);
if (a == 0) break;
showMsg(receiveService.RemoteEndPoint + "发来消息: " + Encoding.UTF8.GetString(by));
}
}
//将内容显示到消息框当中
static void showMsg(string str) {
Console.WriteLine(str+"\n");
}
}
}
分别运行后出现这个状况
找了半天没有找到原因,求各位大神帮帮忙啊!!!
2 个解决方案
#1
找到原因了,就是那个Socket.Accept()方法返回一个新的socket我没有接受用的还是原来的那个Socket所以才会出现这个原因
#2
楼主你怎么解决的。。我也遇到了这个问题。。但我是在数据发送的时候报错
#1
找到原因了,就是那个Socket.Accept()方法返回一个新的socket我没有接受用的还是原来的那个Socket所以才会出现这个原因
#2
楼主你怎么解决的。。我也遇到了这个问题。。但我是在数据发送的时候报错