using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace MyClient
{
public partial class Form1 : Form
{
Socket socketSend;
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;//取消跨线程检查
}
//选择音频路径
private void selectPath(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == DialogResult.OK)
MessageBox.Show(dlg.FileName);
}
//连接服务器并发送本地音频文件
private void connectAndSend(object sender, EventArgs e)
{
//连接服务器
try
{
//创建负责通信的Socket
socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(txtServer.Text);
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
//获得要连接的远程服务器应用程序的IP地址和端口号
socketSend.Connect(point);
ShowMsg("连接成功");
//开启一个新的线程不停的接收服务端发来的消息
Thread th = new Thread(Recive);
th.IsBackground = true;
th.Start();
}
catch
{ }
//发送本地音频
byte[] buffer = null;//文件的存放数组
string path = pathValue.Text;//读取文件成字节流
FileStream fileStream = File.OpenRead(path);
using (BinaryReader binaryReader = new BinaryReader(fileStream))
{
buffer = new byte[fileStream.Length];
binaryReader.Read(buffer, 0, buffer.Length);
}
socketSend.Send(buffer);
}
void Recive()
{
while (true){
try {
byte[] buffer = new byte[1024 * 1024 * 3];
int r = socketSend.Receive(buffer);
if (r == 0){break; } //实际接收到的有效字节数
string s = Encoding.UTF8.GetString(buffer, 0, r);
ShowMsg(socketSend.RemoteEndPoint + ":" + s);
}
catch (Exception e){
Console.WriteLine(e.Message);
ShowMsg(e.Message);
}
}
}
void ShowMsg(string str)
{
txtLog.AppendText(str + "\r\n");
}
}
}
winform------winform实现tcp客户端
于 2019-12-11 16:03:33 首次发布