C/S結構的通信:
客戶端:
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;
namespace TcpClient
{
public partial class Form1 : Form
{
public string serverIP = "127.0.0.1";
public int serverPort = 8888;
public IPAddress serverIPAddress;
public System.Net.Sockets.TcpClient tcpClient;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
serverIP = ipbox.Text;
serverIPAddress = IPAddress.Parse(serverIP);
serverPort = int.Parse(portbox.Text);
tcpClient = new System.Net.Sockets.TcpClient();
tcpClient.Connect(serverIPAddress,serverPort);
if (tcpClient == null)
{
MessageBox.Show("無法連接到服務器,請重試!",
"錯誤",
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
else
{
// 獲取一個和服務器關聯的網絡流
NetworkStream networkStream = tcpClient.GetStream();
// 給服務器發送用戶名
byte[] userName_byte = Encoding.Unicode.GetBytes(userNameBox.Text.Trim());
networkStream.Write(userName_byte,0,userName_byte.Length);
networkStream.Flush();
// 讀取服務器返回的信息
byte[] inforBuffer = new byte[100];
networkStream.Read(inforBuffer,0,inforBuffer.Length);
networkStream.Flush();
string resultFromServer = Encoding.Unicode.GetString(inforBuffer);
this.statusbox.Text = resultFromServer;
}
}
}
}
服務器端:
[html] view plaincopy
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace TcpServer
{
class Listener
{
public TcpListener tcpListener;
public int port = 8888;
public IPAddress ipAddress = IPAddress.Parse("10.108.13.27");
public void Start()
{
tcpListener = new TcpListener(ipAddress,port);
tcpListener.Start();
Console.WriteLine("begin listen port {0}",port);
while (true)
{
byte[] buffer = new byte[100];
Socket newClient = tcpListener.AcceptSocket();
newClient.Receive(buffer);
string userName = Encoding.Unicode.GetString(buffer).TrimEnd('\0');
Console.WriteLine("user :{0} login",userName);
newClient.Send(Encoding.Unicode.GetBytes("success"));
Thread threadClient = new Thread(new ParameterizedThreadStart(clientProcess));
threadClient.Start(newClient);
}
}
public void clientProcess(object info)
{
Socket socket = info as Socket;
}
}
}