首先要做的事建立SOCKET,要建立之前,我们需要用IPEndPoint来指出服务器的IP和开放的端口号。这里有个关键的问题就是端口号。尽量不要用那些比较经典的端口,比如80啥的,这是我遇到的第一个问题。不能重复使用,所以选择比较偏僻的端口比较保险,不然又莫名其妙的报错了。建立好SOCKET后用循环语句侦听端口,看有没有客户端访问进来。有的话,就要新建一个连接SOCKET对象,调用accept()方法,使得连接被允许,然后就是传数据啦。。。其实很简单,所有的数据以字节数组形式传送,所以发送方要对字符串进行编码,用到了byte[] bytr=Encoding.ASCII.GetBytes(string.ToArray) 这里的string是你定义的字符串,即你想传的。接收方则要预先定义一个字节数组,用来存放你要接受的数据,然后调用receive方法。客户端的其他部分和服务器类似,其实关键是通过SOCKET建立起来链接那个部分,即制定IPEndPoint那要搞清楚客户端和服务器端各是干什么的,该定义些什么就行。简单的代码如下:
服务器:
using System;
using System.Collections.Generic;using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace GameServer
{
class Program
{
static void Main(string[] args)
{
Socket theConn;
IPAddress serverIp = IPAddress.Parse("127.0.0.1");
string Port = "8001";
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint serverIpEnd = new IPEndPoint(serverIp, Int32.Parse(Port));
serverSocket.Bind(serverIpEnd);
serverSocket.Listen(100);
while (true)
{
theConn = serverSocket.Accept();
byte[] receive = new byte[1024];
int i = theConn.Receive(receive, 0, theConn.Available, SocketFlags.None);
//string id = Encoding.ASCII.GetString(receive, 0, i);
string id = Encoding.GetEncoding("GB2312").GetString(receive, 0, i);
Console.Write(id);
theConn.Close();
}
}
}
}
客户端:
using System;using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace GameClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
IPAddress serverIp = IPAddress.Parse("127.0.0.1");
string Port = "8001";
IPEndPoint serverhost = new IPEndPoint(serverIp, Int32.Parse(Port));
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
client.Connect(serverhost);
}
catch
{
MessageBox.Show("链接失败");
return;
}
string id = textBox_id.Text;
//string pas = textBox_pas.Text;
// byte[] byteId = Encoding.ASCII.GetBytes(id.ToCharArray());
byte[] byteId = Encoding.GetEncoding("GB2312").GetBytes(id.ToCharArray());
//byte[] bytePas = Encoding.ASCII.GetBytes(pas.ToCharArray());
client.Send(byteId, 0, byteId.Length, SocketFlags.None);
test.Text = Convert.ToString(byteId.Length);
//client.Send(bytePas, 0, bytePas.Length, SocketFlags.None);
client.Close();
}
}
}
Encoding.GetEncoding("GB2312").GetBytes(id.ToCharArray())和string id = Encoding.GetEncoding("GB2312").GetString(receive, 0, i)可以进行字符字母和文字的传输。