WebService里的调用Socket的问题 请大家帮忙看看 谢谢
在WebService里定义了一个公共的Socket类,用来做TCP/IP连接
WebService里有2个[WebMethod],ConnectServer(string ip, int port)用来连接tcp/ip,SendMsg()用来再在TCP/IP连接上的情况下向tcp/ip服务端发送消息。
WebService里的代码为:
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
/// <summary>
/// Convert 的摘要说明
/// </summary>
[WebService(Namespace = "TcpTest")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Convert : System.Web.Services.WebService {
public Socket Soc;
public Convert () {
//如果使用设计的组件,请取消注释以下行
//InitializeComponent();
}
[WebMethod]
public bool ConnectServer(string ip, int port)
{
if (Context.Cache["Soc"] == null)
{
try
{
IPAddress ipaddress = IPAddress.Parse(ip);//转换IP地址
IPEndPoint ipe = new IPEndPoint(ipaddress, port);
Soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//建立连接
Soc.Connect(ipe);
return true;
}
catch (SocketException)
{
Context.Cache.Remove("Soc");
return false;
}
}
else
{
return false;
}
}
[WebMethod]
public void SendMsg()
{
byte[] testStr = { 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00 };
Soc.Send(testStr);
}
}
现在做了一个WINFORM(C#)测试程序来调用这个WEBSERVICE
WINFORM上有2个按纽,一个用来tcp/ip,一个用来发消息
代码如下:
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WindowsApplication4.CtiWebReference;
namespace WindowsApplication4
{
public partial class Form1 : Form
{
CtiWebReference.Convert tcp = new CtiWebReference.Convert();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)//连接tcp/ip
{
bool a;
a = tcp.ConnectServer("127.0.0.1", 9000);
}
private void button2_Click(object sender, EventArgs e)//发送消息
{
tcp.SendMsg();
}
}
}
测试时button1_Click可以连接调用tcp/ip,但是再做button2_Click的时候会出错,提示说:System.Web.Services.Protocols.SoapException: 服务器无法处理请求。 ---> System.NullReferenceException: 未将对象引用设置到对象的实例。
在 Convert.SendMsg() 位置 c:\Documents and Settings\lihaoru\桌面\WebServiceTest\App_Code\Convert.cs:行号 63
--- 内部异常堆栈跟踪的结尾 ---
请问应该怎么解决这个问题,可以在WebService里做OpenConnect连接之后用SendMsg发送消息
请大家帮忙看看 谢谢了