求一个简单的基于TCP/IP的Socket通讯例子

倒大霉的上帝 2010-01-20 02:28:25
如题:求一个简单的基于TCP/IP的Socket传输例子。要求有客户端和服务器端两个程序。可传输文字和文件。
谢谢各位大虾!
...全文
236 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
倒大霉的上帝 2010-01-20
  • 打赏
  • 举报
回复
先结贴做个记号,不懂的再开贴问。
打转的风铃 2010-01-20
  • 打赏
  • 举报
回复
hh
qqiuzaihui 2010-01-20
  • 打赏
  • 举报
回复
//======================================================================
//
// Copyright : SHANGHAI HOMEN INTELLIGENT SYSTEM Co.,LTD.
// All rights reserved
//
// Formname : TcpSend
// Description : TcpSend示例之发送数据 C#高级编程(第四版) P1145
//
// created by 邱在辉 at 2010-1-7 15:40:30
//
//======================================================================
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.Sockets;
using System.IO;

namespace BasicWebClient
{
public partial class TcpSend : Form
{
private OpenFileDialog chooseOpenFileDialog = new OpenFileDialog();
private string chosenFile = "..\\..\\TcpSend.cs";

public TcpSend()
{
InitializeComponent();

chooseOpenFileDialog.FileOk += new CancelEventHandler(OnOpenFileDialogOK);
}

private void btnSend_Click(object sender, EventArgs e)
{
try
{
// 使用主机名和端口号创建TcpClient
TcpClient tcpClient = new TcpClient(txtHost.Text, Int32.Parse(txtPort.Text));
NetworkStream ns = tcpClient.GetStream();
FileStream fs = File.Open(chosenFile, FileMode.Open);

int data = fs.ReadByte();
while (data != -1) // 循环读取所有字节, 并发送给网络流
{
ns.WriteByte((byte)data);
data = fs.ReadByte();
}
fs.Close(); // 关闭所有打开的文件, 连接和流
ns.Close();
tcpClient.Close();
}
catch (Exception ex)
{
MessageBox.Show("Unable to process the request because " + "the following problem occurred:\n" +
ex.Message, "Exception occurred");
}
}

private void btnSel_Click(object sender, EventArgs e)
{
chooseOpenFileDialog.ShowDialog();
}
void OnOpenFileDialogOK(object Sender, CancelEventArgs e)
{
chosenFile = chooseOpenFileDialog.FileName;
this.Text = Path.GetFileName(chosenFile);
}
}
}


//======================================================================
//
// Copyright : SHANGHAI HOMEN INTELLIGENT SYSTEM Co.,LTD.
// All rights reserved
//
// Formname : TcpSend
// Description : TcpReceive示例之接收数据 C#高级编程(第四版) P1146
//
// created by 邱在辉 at 2010-1-7 16:10:30
//
//======================================================================
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.IO;
using System.Threading;

namespace BasicWebClient
{
public partial class TcpReceive : Form
{
private Thread thread;

protected delegate void UpdateDisplayDelegate(string text);
public TcpReceive(bool bSocket)
{
InitializeComponent();

if (bSocket)
thread = new Thread(new ThreadStart(SocketListen));
else
thread = new Thread(new ThreadStart(TcpListen));
thread.Start();
}
// 在后台线程中使用TcpListener待进来的连接. P1147
public void TcpListen()
{
IPAddress localAddr = IPAddress.Parse("192.168.1.109");
Int32 port = 2112;
TcpListener tcpListener = new TcpListener(localAddr, port);
tcpListener.Start();

// 使用AccpeTcpClient()返回的TcpClient对象打开一个新流, 进行读取.
TcpClient tcpClient = tcpListener.AcceptTcpClient();
NetworkStream ns = tcpClient.GetStream();
StreamReader sr = new StreamReader(ns);
string result = sr.ReadToEnd();
Invoke(new UpdateDisplayDelegate(UpdateDisplay), new object[] { result });

tcpClient.Close();
tcpListener.Stop();
}
// 使用Socket接收数据 P1149
private void SocketListen()
{
// 构造函数的参数需要为使用TCP协议的流套接字指定IP寻址模式.
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// 把监听器的套接字绑定到一个端口上, 开始监听传入的连接
listener.Bind(new IPEndPoint(IPAddress.Any, 2112));
listener.Listen(0);

//当传入一个连接时, 使用Accept()方法创建一个新的套接字, 来处理该连接
Socket socket = listener.Accept();
// 为套接字创建一个StreamReader实例, 读取传入的数据
Stream netStream = new NetworkStream(socket);
StreamReader reader = new StreamReader(netStream);

string result = reader.ReadToEnd();
Invoke(new UpdateDisplayDelegate(UpdateDisplay), new object[] { result });

socket.Close();
listener.Close();
}

// 显示数据
public void UpdateDisplay(string text)
{
this.textBox1.Text = text;
}
}
}
j_f0001 2010-01-20
  • 打赏
  • 举报
回复
服务器端: s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Bind(new IPEndPoint(IPAddress.Any, 8089));
s.Listen(0);
while (true)
{
Socket c = s.Accept();
byte[] buff = new byte[c.EndReceive];
c.BeginReceive(buff, 0, buff.Length, SocketFlags.None, new AsyncCallback(SendCallBack), "dd");
string str = Encoding.UTF8.GetString(buff);

}

客户端: c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
c.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8089));
string str = "this is a temp";
byte[] buff = Encoding.UTF8.GetBytes(str);
c.Send(buff, 0, buff.Length, SocketFlags.None, new AsyncCallback(SendCallBack),"dd");
烈火蜓蜻 2010-01-20
  • 打赏
  • 举报
回复
MSDN里,搜索一下,Socket编程
指间的风 2010-01-20
  • 打赏
  • 举报
回复
http://www.isstudy.com/cjc/2157.html
指间的风 2010-01-20
  • 打赏
  • 举报
回复
http://www.52bc.net/html/biancheng/C_/20090904/257.html

110,533

社区成员

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

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

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