游戏客户端编程
- 1.代码实现
-
- 2.显示消息
- 3.发送信息
- 4.播放背景音乐
- 5.变换游戏背景图片
- 6.参考
1.代码实现
服务器连接
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("服务器未启动!");
}
发送按钮
原来没有这个控件,需要自己添加
代码:
private void button12_Click_1(object sender, EventArgs e)
{
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("连接已断开");
}
}
2.显示消息
1)连接成功后,可以将服务器发来的消息不停地显示在 listbox 中;
3.发送信息
- 客户端要发给服务器的数据,通过 textbox输入 或者点击button;
4.播放背景音乐
代码:
SoundPlayer sp = new SoundPlayer();
sp.SoundLocation = @"音乐.wav";
sp.PlayLooping();
头文件:
using System.Media;
5.变换游戏背景图片
代码:
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 3000;
int i = 0;
timer.Elapsed += delegate
{
i++;
Image image = Image.FromFile(i + ".png");
pictureBox1.Image = image;
if (i == 3) i = 0;
};
timer.Start();
6.参考
1.game1.zip
2.C#实现网游客户端与服务器的连接
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)