日期:2014-05-20 浏览次数:20713 次
package com.taoge.socke;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPEchoServer {
private static final int ECHOMAX=255;//max size of echo datagram
public static void main(String[] args) throws IOException {
/*
if(args.length!=1){
throw new IllegalArgumentException("Parameter(s):<Port>");
}
*/
//int servPort=Integer.parseInt(args[0]);
int servPort = 5555;
//1.创建一个DatagramSocket实例,指定本地端口号,可以选择指定本地地址
DatagramSocket socket=new DatagramSocket(servPort);
DatagramPacket packet=new DatagramPacket(new byte[ECHOMAX],ECHOMAX);
while(true){
//2.使用DatagramSocket的receive方法来接收一个DatagramPacket实例。
socket.receive(packet);
System.out.println("Handling client at "+packet.getAddress().getHostAddress()+" on port "+packet.getPort());
System.out.println("包的数据:" + new String(packet.getData()));
socket.send(packet);
packet.setLength(ECHOMAX);
//socket.close();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace ConsoleApplication1
{
/**
* C# 版本UDP客户端,用与连接Java服务器端发送数据。
* */
class Program
{
static void Main(string[] args)
{
int SenderPort = 5555;
String host = "127.0.0.1";
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipepoit = new IPEndPoint(ip,SenderPort);
UdpClient udpClient = new UdpClient(SenderPort);
udpClient.Connect(ip,SenderPort);
Byte[] sendByts = Encoding.ASCII.GetBytes("welcome to chengdu!!");
//udpClient.Send(sendByts,sendByts.Length);
udpClient.Send(sendByts, 255);
//IPEndPoint RemoteIpEndPoint = new IPEndPoint(ip, 0);
//Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
//string returnData = Encoding.ASCII.GetString(receiveBytes);
//Console.WriteLine("This is the message you received " + returnData.ToString());