C\#에서 UDP 통신 인 스 턴 스 사용

네트워크 통신 프로 토 콜 의 UDP 통신 은 연결 되 지 않 은 통신 으로 클 라 이언 트 가 데 이 터 를 보 내기 전에 서버 측 과 연결 할 필요 가 없고 서버 측 이 온라인 이 아니 더 라 도 보 낼 수 있 지만 서버 측 이 데 이 터 를 받 을 수 있다 는 보장 은 없다.본 고의 실례 는 C\#를 바탕 으로 실 현 된 UDP 통신 이다.구체 적 인 기능 코드 는 다음 과 같다.
서버 쪽 코드 는 다음 과 같 습 니 다:

static void Main(string[] args) 
{ 
  UdpClient client = null; 
  string receiveString = null; 
  byte[] receiveData = null; 
  //         ,IP         ,   client.Receive(ref remotePoint)                
  IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0); 

  while (true) 
  { 
 client = new UdpClient(11000); 
 receiveData = client.Receive(ref remotePoint);//     
 receiveString = Encoding.Default.GetString(receiveData); 
 Console.WriteLine(receiveString); 
 client.Close();//     
  } 
}

클 라 이언 트 코드 는 다음 과 같 습 니 다.

static void Main(string[] args) 
{ 
  string sendString = null;//        
  byte[] sendData = null;//         
  UdpClient client = null; 

  IPAddress remoteIP = IPAddress.Parse("127.0.0.1"); 
  int remotePort = 11000; 
  IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);//          

  while (true) 
  { 
 sendString = Console.ReadLine(); 
 sendData = Encoding.Default.GetBytes(sendString); 

 client = new UdpClient(); 
 client.Send(sendData, sendData.Length, remotePoint);//           
 client.Close();//     
  } 
}

프로그램의 최종 실행 효 과 는 다음 과 같 습 니 다.

좋은 웹페이지 즐겨찾기