高分请教。有关C#中的sokcet编程问题

yx718 2007-10-29 10:44:54
最近刚学C#,遇到有关socket的问题,有请高手帮帮忙。
目的是想实现一个client/server最简单的通信,采用socket编程。
问题主要出现在客户端代码,服务器断能够接收到客户端的数据,但是客户端的receive总是没有反应。
如果把 if (connSocket.Available == 0) 这个判断去掉而直接receive的话,客户端程序会死掉。
不知道问题在那儿,100分有请高手解答!分数不是问题!不够再加!电脑旁等候回复信息。

//server端主要代码如下:
//省略了部分无关紧要的代码。
namespace myServer
{
public partial class frmMain : Form
{
private BackgroundWorker bwListener;
private Socket listenerSocket;
private IPAddress serverIP;
private int serverPort;
delegate void SetTextCallback(string text);
private Socket socket;

public frmMain()
{
InitializeComponent();

bwListener = new BackgroundWorker();
bwListener.WorkerSupportsCancellation = true;
bwListener.DoWork += new DoWorkEventHandler(StartToListen);
bwListener.RunWorkerAsync();

txtServerIP.Text = "192.168.1.10";
serverIP = IPAddress.Parse(txtServerIP.Text);
serverPort = 8000;

}

private void StartToListen(object sender, DoWorkEventArgs e)
{

string sendToClient = "OK! You can exit now!!!";
Byte[] bytesSentToClient = Encoding.ASCII.GetBytes(sendToClient);
Byte[] bytesReceived = new Byte[256];

this.listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
this.listenerSocket.Bind(new IPEndPoint(this.serverIP, this.serverPort));
this.listenerSocket.Listen(200);

int bytes = 0;
string page = "Client's information: ";

while (true)
{
try
{
socket = this.listenerSocket.Accept();
SetText(((IPEndPoint)socket.RemoteEndPoint).Address.ToString());

do
{

bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0);
int sendCount = 0;
socket.SendTimeout = 1000;
//在这里向客户端发送一句话,能够发送成功
sendCount = socket.Send(bytesSentToClient);
if (sendCount > 0)
MessageBox.Show("send success");
page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
while (bytes > 0);
}
catch (SocketException se)
{
MessageBox.Show(se.Message + "\r\n错误代码: " + se.ErrorCode);
return;
}
catch (Exception ee)
{
MessageBox.Show(ee.Message + "\r\n");
return;
}

DisconnectServer();
}
}

public void DisconnectServer()
{
this.bwListener.CancelAsync();
this.bwListener.Dispose();
this.listenerSocket.Close();
GC.Collect();
}

}
}

//-----------------------------------------------------------------------------
//客户端主要代码如下:
namespace test
{
public partial class ClientForm : Form
{
private Socket connSocket;
delegate void SetTextCallback(string text);

public ClientForm()
{
InitializeComponent();
}

private void btnConServer_Click(object sender, EventArgs e)
{
string host = "192.168.1.10";
int port = 8000;

host = txtServerIP.Text;
string result = SocketSendReceive(host, port);
}

private static Socket ConnectSocket(string server, int port)
{
Socket s = null;
IPHostEntry hostEntry = null;

// Get host related information.
hostEntry = Dns.GetHostEntry(server);

foreach (IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
Socket tempSocket =
new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

try
{
tempSocket.Connect(ipe);
}
catch (SocketException e)
{
MessageBox.Show(e.Message + "\r\n错误代码: " + e.ErrorCode);
return null;
}

if (tempSocket.Connected)
{
s = tempSocket;
break;
}
else
{
continue;
}
}
return s;
}

// This method requests the home page content for the specified server.
private string SocketSendReceive(string server, int port)
{
string request = "connecting host: " + server +
"\r\n";
Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
Byte[] bytesReceived = new Byte[1024];

// Create a socket connection with the specified server and port.
connSocket = ConnectSocket(server, port);

if (connSocket == null)
return ("Connection failed");

// Send request to the server.
connSocket.Send(bytesSent, bytesSent.Length, 0);

// Receive the server home page content.
int bytes = 0;
string page = "receiving data from host " + server + " \r\n";

// The following will block until te page is transmitted.
do
{
try
{
connSocket.ReceiveTimeout = 1000;
if (connSocket.Available == 0)
{
MessageBox.Show("没有数据可接收");
//return null;
}

/**********问题出现在这里*******/
//Receive总是不能成功!

bytes = connSocket.Receive(bytesReceived, bytesReceived.Length, 0);
if (bytes > 0)
MessageBox.Show("接收成功");
page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
catch (SocketException se)
{
MessageBox.Show(se.Message + "\r\n错误代码: " + se.ErrorCode);
return null;
}
catch
{
MessageBox.Show("错误代码!");
return null;
}
}
while (bytes > 0);

return page;
}
}
}
...全文
187 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
Love_My 2007-10-30
  • 打赏
  • 举报
回复
太长 参考下些代码:


IPHostEntry ipHost = Dns.Resolve(地址);
TcpClient tcpClient = new TcpClient(ipHost.HostName , 端口);
NetworkStream Stream= tcpClient.GetStream(); //主动连接

然后可以
StreamReader stReader = new StreamReader(Stream); //读取流

用stReader监听数据
yx718 2007-10-30
  • 打赏
  • 举报
回复
Love_My 你好,我现在采用的模型大致如下:

server client
------- -------
socket() socket()
bind()
listen()
accept()<---connect()
receive()<--sned()
send()----->receive()
close() close()

C#中也提供了这些方法,我希望直接通过这个模型中的方法来实现客户端和服务器端得最简单的通信(只要相互能够发送一个“hello”就行)。
现在的问题是,服务器端receive成功,但是客户端receive失败。

你给的这个方法我会试一下的,但是我很想知道我现在的问题出现在哪里?
yx718 2007-10-30
  • 打赏
  • 举报
回复
果然是因为异步接收问题,多谢各位,不胜感激,揭帖!
我不懂电脑 2007-10-30
  • 打赏
  • 举报
回复
这个方法是可行的。

using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;

// State object for receiving data from remote device.
public class StateObject {
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}

public class AsynchronousClient {
// The port number for the remote device.
private const int port = 11000;

// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone =
new ManualResetEvent(false);
private static ManualResetEvent sendDone =
new ManualResetEvent(false);
private static ManualResetEvent receiveDone =
new ManualResetEvent(false);

// The response from the remote device.
private static String response = String.Empty;

private static void StartClient() {
// Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
// The name of the
// remote device is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

// Create a TCP/IP socket.
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);

// Connect to the remote endpoint.
client.BeginConnect( remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();

// Send test data to the remote device.
Send(client,"This is a test<EOF>");
sendDone.WaitOne();

// Receive the response from the remote device.
Receive(client);
receiveDone.WaitOne();

// Write the response to the console.
Console.WriteLine("Response received : {0}", response);

// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();

} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}

private static void ConnectCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the state object.
Socket client = (Socket) ar.AsyncState;

// Complete the connection.
client.EndConnect(ar);

Console.WriteLine("Socket connected to {0}",
client.RemoteEndPoint.ToString());

// Signal that the connection has been made.
connectDone.Set();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}

private static void Receive(Socket client) {
try {
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;

// Begin receiving the data from the remote device.
client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}

private static void ReceiveCallback( IAsyncResult ar ) {
try {
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket client = state.workSocket;

// Read data from the remote device.
int bytesRead = client.EndReceive(ar);

if (bytesRead > 0) {
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));

// Get the rest of the data.
client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
new AsyncCallback(ReceiveCallback), state);
} else {
// All the data has arrived; put it in response.
if (state.sb.Length > 1) {
response = state.sb.ToString();
}
// Signal that all bytes have been received.
receiveDone.Set();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}

private static void Send(Socket client, String data) {
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);

// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), client);
}

private static void SendCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the state object.
Socket client = (Socket) ar.AsyncState;

// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", bytesSent);

// Signal that all bytes have been sent.
sendDone.Set();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}

public static int Main(String[] args) {
StartClient();
return 0;
}
}
winooo 2007-10-30
  • 打赏
  • 举报
回复
接收数据为异步接收.
可以EMAIL一个完整的C#版本的服务与客户端程序给你.C++的就不能给.:)功能强大.呵
wsj1983920 2007-10-30
  • 打赏
  • 举报
回复
mark
wuhq030710914 2007-10-30
  • 打赏
  • 举报
回复
接收放到另外一个线程中
Thread t=new Thread(new ThreadStart(aa));
t.start();
public void aa()
{
//接收程序
}
achilis 2007-10-29
  • 打赏
  • 举报
回复
有没有windows版本的啊
honey52570 2007-10-29
  • 打赏
  • 举报
回复
sf

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧