当前位置:
文档之家› tcp和udp的区别,测试实例.doc
tcp和udp的区别,测试实例.doc
public static void main(String[] args) throws Exception { UDPClient client = new UDPClient();
String serverHost = ”127.001“;
int serverPort = 3366;
client.send(serverHost, serverPort,(”你好!H).getBytes()); String infb = client.receive(serverHost, serverPort); System.out.println("服务端冋应数据:” +info);
*@author zzy
*/
public final DatagramPacket send(final String host, final int port, final byte[] bytes) throws IOException {
DatagramPacket dp = new DatagramPacket(bytes, bytes length, Inet Address .getByName(host), port);
*@author zzy
*/
public UDPClient() throws Exception { ds = new DatagramSocket();
*@return返回超时时间
*@throws tion
*@author zzy
*/
public final int getSoTimeout() throws Exception { return ds.getSoTimeout();
import .DatagramSocket;
import .InetAddress;
public class UDPClient {
private bytef]buffer
private DatagramSocket ds
*构造函数,创建UDP客户端
*@throws Exception
Socket s = new Socket(" 127.0.0.1", 8083);
OutputStreamWriter w = new OutputStreamWriter(s.getOutputStream());
w.write(”这里是客户端,Hello服务器,准备发到服务器端“);w.flush();
System.err.println(HA client has heen connected.M);
System.err.println(M这里是服务器端"+TCPServer.class); InputStreamReader r = new InputStreamReader(s.getInputStream()); int c = 0;
while ((c = r.read()) > -1) {
System.err.print((char) c);
r.close();
s.close();
package com.server;
import java.io.IOException;
import .DatagramPacket;
ds.send(dp);
return dp;
}
*接收从指定的服务端发回的数据.
*
*@param Ihost
*服务端主机
*@param lport
*服务端端口
*@return返回从指定的服务端发回的数据.
*@throws Exception
*@author zzy
public final String receive(final String lhost, final int lport) throws Exception {
}
public final DatagramSocket getSocket() {
return ds;
*向指定的服务端发送数据信息.
*
*@param host
*服务器主机地址
*@param port
*服务端端口
*@param bytes
*发送的数据信息
*@return返冋构造后俄数据报
*@throws IOException
package com.server;
import java.io.OutputStreamWriter;
import .Socket;
public class TCPClient {
/**
*@param args
*@author zzy
*/
public static void main(Stringn args) throws Exception {
w.close();
s.close();
package com.server;
import java.ioputStreamReader;
import .ServerSocket;
import .Socket;
public class TCPServer {
/**
*@param args
*@author zzy
*/
public static void main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(8083);
while (true) {
Socket s = ss.accept();
DatagramPacket dp = new DatagramPacket(buffer, bulfer.length); ds.receive(dp);
String info = new String(dp.getData(), 0, dp.getLength());
return info;
*关闭udp连接.
*
*/
public final void close() { try {
ds.close();
} catch (Exception ex) {
ex.printStackTrace();
*测试客八端发包和接收冋应信息的方法.
@param args @throws Exception @author zzy
import .SocketException;
*@author zzy
*/
public class UDPServer {
}
package com.server;
import java.io.IOException;
import .DatagramPacket; import .DatagramSocket;
import .InetAddress;
import .InetSocketAddress;