一、项目创建以及页面设置
(一)新建项目
二、窗体设计
打开窗口设计页面,双击窗体可以跳转至代码编辑页面,将Form1()替换成以下代码:
private NetworkStream stream;
private TcpClient tcpClient = new TcpClient();
public Form1()
{
InitializeComponent();
try
{
tcpClient.Connect("10.1.230.74", 3900);
listBox1.Items.Add("连接成功!");
stream = tcpClient.GetStream();
byte[] data = new byte[1024];
if (stream.CanRead)
{
int len = stream.Read(data, 0, data.Length);
string msg = Encoding.Default.GetString(data, 0, data.Length);
string str = "\r\n";
char[] str1 = str.ToCharArray();
string[] msg1=msg.Split(str1);
for(int j = 0; j < msg1.Length; j++)
{
listBox1.Items.Add(msg1[j]);
}
}
}
catch
{
listBox1.Items.Add("服务器未启动!");
}
}
在头文件中添加using System.Net.Sockets;
代码实现
(1)实现连接到服务器并接受数据
双击进入游戏的Button 代码:
private void button1_Click(object sender, EventArgs e)
{
try
{
tcpClient.Connect("10.1.230.41", 3900);
listBox1.Items.Add("连接成功!");
stream = tcpClient.GetStream();
byte[] data = new byte[1024];
if (stream.CanRead)
{
int len = stream.Read(data, 0, data.Length);
string msg = Encoding.Default.GetString(data, 0, data.Length);
string str = "\r\n";
char[] str1 = str.ToCharArray();
string[] msg1 = msg.Split(str1);
for (int j = 0; j < msg1.Length; j++)
{
listBox1.Items.Add(msg1[j]);
music_play();
}
}
}
catch
{
listBox1.Items.Add("连接失败!");
}
}
(2)实现客户端发送数据到服务器 双击发送的button 代码:
private void button12_Click(object sender, EventArgs e)
{
music_play();
if (tcpClient.Connected)
{
string msg = textBox1.Text;
Byte[] outbytes = System.Text.Encoding.Default.GetBytes(msg + "\n");
stream.Write(outbytes, 0, outbytes.Length);
byte[] data = new byte[1024];
if (stream.CanRead)
{
int len = stream.Read(data, 0, data.Length);
string msg1 = Encoding.Default.GetString(data, 0, data.Length);
string str = "\r\n";
char[] str1 = str.ToCharArray();
string[] msg2 = msg1.Split(str1);
for (int j = 0; j < msg2.Length; j++)
{
listBox1.Items.Add(msg2[j]);
}
}
}
else
{
listBox1.Items.Add("连接已断开");
}
textBox1.Clear();
}
播放背景音乐,在项目引用里增加COM组件WindowsMediaPlayer
private void music_play()
{
WMPLib.WindowsMediaPlayer Player = new WMPLib.WindowsMediaPlayer();
Player.URL = @"D:\CloudMusic\阿保剛 - Karma -Piano version-.mp3";
Player.controls.play();
}
图片代码
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 30000;
int i = 0;
timer.Elapsed += delegate
{
i++;
Image image = Image.FromFile(i + ".jpg");
pictureBox1.Image = image;
if (i == 3) i = 0;
};
timer.Start();
运行界面
参考链接
https://blog.csdn.net/u011889811/article/details/43356075 https://blog.csdn.net/weixin_45888898/article/details/109788760
|