昨天看了下视频中老师讲Socket通信使用,照着敲却出现了问题。问题如下:
主要代码如下,大家帮我看看:
服务端:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace SocketProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Thread threadWatch = null;//负责监听的线程
Socket socketwathc = null;//负责监听的套接字
private void btnLink_Click(object sender, EventArgs e)
{
//创建服务端负责监听的套接字,参数(IPv4,流式传输,TCP协议),
socketwathc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//获得文本框中的IP
IPAddress addresss = IPAddress.Parse(tbxIP.Text.Trim());
//创建含有IP和Port的网络节点对象
IPEndPoint endport=new IPEndPoint(addresss,int.Parse(tbxPort.Text.Trim()));
//
socketwathc.Bind(endport);
//设置监听队列的长度
socketwathc.Listen(10);
//开始监听客户端连接请求,Accept()方法会截断当前线程。为了让它不要截断当前线程,可以让他独占线程
//将方法Accept方法单独作为一个线程
threadWatch = new Thread(Watchconnction);
threadWatch.IsBackground = true;
threadWatch.Start();
ShowMsg("服务端启用监听成功");
}
void Watchconnction()
{
while (true)//持续不断的监听客户端的连接;
{
Socket connectiong = socketwathc.Accept();
ShowMsg("客户端连接成功");
}
}
void ShowMsg(string msg)
{
this.txtMsg.AppendText(msg + "\r\n");
}
private void btnSend_Click(object sender, EventArgs e)
{
string strmsg = this.txtMsgSend.Text.Trim();
byte[] arrary=Encoding.UTF8.GetBytes(strmsg);
socketwathc.Send(arrary);
ShowMsg("发送了数据:" + strmsg);
}
}
}
客户端:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ClientProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Thread threadclient = null;//定义一个数组,用于为clientSocket.Receive()方法创建独立线程;
Socket clientSocket = null;//客户端套接字
private void btnClient_Click(object sender, EventArgs e)
{
IPAddress address=IPAddress.Parse(tbxIP.Text.Trim());
IPEndPoint endport = new IPEndPoint(address, int.Parse(tbxPort.Text.Trim()));
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(endport);//连接到服务端
threadclient = new Thread(RecMsg);
threadclient.IsBackground = true;
threadclient.Start();
}
void ShowMsg(string msg)
{
this.txtRec.AppendText(msg + "\r\n");
}
void RecMsg()
{
while (true)
{
//定义一个2M的字节数组(缓存接收的数据)
byte[] arraryrec = new byte[1024 * 1024 * 2];
//接收服务端发来的消息的长度
int strlength= clientSocket.Receive(arraryrec);
//将接收来的消息转化为String
string strmsgrec = Encoding.UTF8.GetString(arraryrec,0,strlength);
//显示消息
ShowMsg(strmsgrec);
}
}
}
}
这问题没解决没法往下走了:急求各位大神解决,感激不尽!!!!!
|
-
1.jpg
(213.03 KB, 下载次数: 0)
运行时
-
2.jpg
(59.75 KB, 下载次数: 0)
错误信息
|