c# 如何实现端口数据的 通信

smgzfhxy 2009-04-09 10:56:31
查阅好多资料也不没看明白怎么操作 '
我只需要向端口发送数据 和接受数据
服务端协议 已经早就存在
是 delphi 开发的
不知道 是否存在语言的对接问题?
还有MSDN 关于socket的代码 我也搞不清楚 怎么用
比如 ---------------------
using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;

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

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

// Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
// an exception that occurs when the host IP Address is not compatible with the address family
// (typical in the IPv6 case).
foreach(IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
Socket tempSocket =
new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

tempSocket.Connect(ipe);

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

// This method requests the home page content for the specified server.
private static string SocketSendReceive(string server, int port)
{
string request = "GET / HTTP/1.1\r\nHost: " + server +
"\r\nConnection: Close\r\n\r\n";
Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
Byte[] bytesReceived = new Byte[256];

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

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

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

// Receive the server home page content.
int bytes = 0;
string page = "Default HTML page on " + server + ":\r\n";

// The following will block until te page is transmitted.
do {
bytes = s.Receive(bytesReceived, bytesReceived.Length, 0);
page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
while (bytes > 0);

return page;
}

public static void Main(string[] args)
{
string host;
int port = 80;

if (args.Length == 0)
// If no server name is passed as argument to this program,
// use the current host name as the default.
host = Dns.GetHostName();
else
host = args[0];

string result = SocketSendReceive(host, port);
Console.WriteLine(result);
}
-------------------------------------------------------------------------------------
我本地一直没有是通 不知道效果是怎么样的
希望大家给予指导谢谢
...全文
125 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
walkghost 2009-04-12
  • 打赏
  • 举报
回复
异步的socket通讯。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SocketTest
{
public partial class Form1 : Form
{
private IPAddress ServerIP;
private IPEndPoint _ipendPoint;
Socket _mySocket;
Socket listen;
Thread listenTH;
Thread thread;
public Form1()
{
InitializeComponent();
}

private void btnStartService_Click(object sender, EventArgs e)
{

//创建socket
ServerIP = IPAddress.Parse(txtServerIP.Text.Trim());
_ipendPoint = new IPEndPoint(ServerIP, int.Parse(txtServerPort.Text.Trim()));
_mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_mySocket.Bind(_ipendPoint);
_mySocket.Listen(102400);
lbServerStateTXT.Text = "Server is started...";

listenTH = new Thread(new ThreadStart(LintenClient));
listenTH.IsBackground = true;
listenTH.Start();

//timer1.Start();
}
private void LintenClient()
{

listen = _mySocket.Accept();
thread = new Thread(new ThreadStart(threadproc));
thread.IsBackground = true;
thread.Start();

}
private void threadproc()
{
byte[] receiveMSG = new byte[10240];

listen.Receive(receiveMSG);




ASCIIEncoding ec = new ASCIIEncoding();
if (ec.GetString(receiveMSG) != "")
{
TXT(ec.GetString(receiveMSG));

}


}

private void btnStopService_Click(object sender, EventArgs e)
{

_mySocket.Close();
lbServerStateTXT.Text = "Server is stop service!";
}

private delegate void ADDMSG(String str);

public void TXT(string str)
{
if (this.InvokeRequired)
{
ADDMSG call = delegate(string s)
{
txtRecive.Text += str;
};
this.Invoke(call, str);
}
else
{
txtRecive.Text += str;
}

string strsend = "Server had recived MSG!";
byte[] bufferSend = new byte[1021];
bufferSend = System.Text.Encoding.Default.GetBytes(strsend);
listen.Send(bufferSend);

listenTH.Abort();
listen.Close();
thread.Abort();
//_mySocket.Close();

}



private void btnSend_Click(object sender, EventArgs e)
{
//发送数据
byte[] sendmsg = new byte[102300];
byte[] receivemsg = new byte[102300];
Socket mysender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
if (txtBoxSendServerPort.Text.Trim()!="")
{
mysender.Connect(txtBoxSendServerIP.Text, int.Parse(txtBoxSendServerPort.Text.Trim()));
}
else
{
mysender.Connect("127.0.0.1", 8888);
}
}
catch (Exception e2)
{
txtRecive.AppendText(e2.Message);
}
sendmsg = Encoding.Default.GetBytes(txtSend.Text);

try
{
mysender.Send(sendmsg);

}
catch (Exception e2)
{
txtRecive.AppendText(e2.Message);
}

try
{
mysender.Close();
}
catch (Exception e2)
{
txtRecive.AppendText(e2.Message);
}
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//listenTH.Abort();
}
}
}

110,545

社区成员

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

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

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