using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace server
{
class Program
{
private static intserver_port = 9000;
private static stringserver_ip = "127.0.0.1";
private static intbuffer_size = 1024;
private static string data =null;
private static byte[]receiveBytes = new byte[buffer_size];
private static stringsendStr="ok";
private static intbytesCount;
private static Socketclient;
static void Main(string[]args)
{
try
{
Socket server_socket = newSocket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
IPAddress ipadd =IPAddress.Parse(server_ip);
IPEndPoint ipe = newIPEndPoint(ipadd, server_port);
server_socket.Bind(ipe);
server_socket.Listen(100);
client =server_socket.Accept();
Console.WriteLine("=========I am waiting for theclient:========== ");
while (true)
{
bytesCount = client.Receive(receiveBytes,receiveBytes.Length, 0); data =Encoding.ASCII.GetString(receiveBytes,0, bytesCount);
Console.WriteLine("Client Said:{0}",data);
sendStr = Console .ReadLine ();
byte[] sendBytes = Encoding.ASCII.GetBytes(sendStr);
client.Send(sendBytes,sendBytes.Length, 0);//向客户端发送信息
}
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
client.Close();
}
}
}
==================
client端
==================
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
usingSystem.Net.Sockets;
namespace client
{
class Program
{
private static intserver_port = 9000;
private static stringserver_ip="127.0.0.1";
private static intbuffer_size=1024;
private static Socketclient_socket = null;
private static stringclientInput="ok";
private static stringclientReceiveStr = null;
private static byte[]clientSendBytes = new byte[buffer_size];
private static byte[]clientReceiveBytes = new byte[buffer_size];
static void Main(string[]args)
{
try
{
client_socket = newSocket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
IPAddress ipadd =IPAddress.Parse(server_ip);
IPEndPoint ipe = newIPEndPoint(ipadd, server_port);
client_socket.Connect(ipe);
while (true )
{
clientInput = Console.ReadLine();
// clientInput = "hello in client";
clientSendBytes =Encoding.ASCII.GetBytes(clientInput);
client_socket.Send(clientSendBytes,clientSendBytes.Length, 0);
int bytes = client_socket.Receive(clientReceiveBytes,clientReceiveBytes.Length, 0);
clientReceiveStr =Encoding.ASCII.GetString(clientReceiveBytes, 0, bytes);
Console.WriteLine("\nServer Said:{0}",clientReceiveStr);
}
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
client_socket.Shutdown(SocketShutdown.Both);
client_socket.Close();
//Console.ReadLine();
}
}
}