C/S structure communication:
Client:
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 button#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 ("unable to connect to the server. Please try again! ",
"Error ",
MessageBoxButtons. OK,
MessageBoxIcon. Exclamation );
}
Else
{
// Obtain a network stream associated with the server
NetworkStream networkStream = tcpClient. GetStream ();
// Send the user name to the server
Byte [] userName_byte = Encoding. Unicode. GetBytes (userNameBox. Text. Trim ());
NetworkStream. Write (userName_byte, 0, userName_byte.Length );
NetworkStream. Flush ();
// Read the information returned by the server
Byte [] inforBuffer = new byte [1, 100];
NetworkStream. Read (inforBuffer, 0, inforBuffer. Length );
NetworkStream. Flush ();
String resultFromServer = Encoding. Unicode. GetString (inforBuffer );
This. statusbox. Text = resultFromServer;
}
}
}
}
Server:
[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;
}
}
}