日期:2014-05-17 浏览次数:20857 次
using System ;
using System .Text ;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace SocketClient
{
class client
{
private static byte[] result = new byte[1024];
static void Main(string[] args)
{
//设定服务器IP地址
IPAddress ip = IPAddress.Parse("127.0.0.1");
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(new IPEndPoint(ip, 8080)); //配置服务器IP与端口
Console.WriteLine("连接服务器成功");
}
catch
{
Console.WriteLine("连接服务器失败,请按回车键退出!");
return;
}
//通过clientSocket接收数据
// int receiveLength = clientSocket.Receive(result);
// Console.WriteLine("接收服务器消息:{0}",Encoding.ASCII.GetString(result,0,receiveLength));
byte[] bytes = new byte[1024];
String input;
while (true) {
input = Console .ReadLine ();
bytes = Encoding .ASCII .GetBytes (input);
clientSocket .Send(bytes);
if(input == "exit"){
break ;
}
}
}
}
}
using System;
using System .Net .Sockets ;
using System .Net ;
using System .Text ;
using System .Threading ;
using System.Collections;
namespace SocketServer{
public class unitysocket {
private static Socket soc ;
private static byte[] buffer = new byte[1024];
static void Main(string[] args){
IPAddress ip = IPAddress.Parse ("127.0.0.1");
IPEndPoint ipep = new IPEndPoint (ip, 8080);
soc = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
soc.Bind (ipep);
soc.Listen (10);
Thread thread = new Thread (new ThreadStart (Redata));
thread .Start ();
}
//接受数据
static void Redata(){
Socket s = soc ;
while(true){
try{
s.Accept();
int rs = s.Available;
s.Receive(buffer,0,rs,SocketFlags .None );
if(rs == 0){
continue ;
}
string rdata = Encoding .ASCII .GetString(buffer).Substring (0,rs);
Console.WriteLine(rdata );
}catch(Exception e ){
Console.WriteLine(e.ToString());
}
}
}
}
}