Java網絡編程的例子

1.UDP編程

1.UDP服務端

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UDPServer {
	public static void main(String[] args) throws SocketException {
		try {
			DatagramSocket server = new DatagramSocket(8888);//服務器監聽端口
			byte[] buf = new byte[1024];
			DatagramPacket packet = new DatagramPacket(buf, buf.length);

			server.receive(packet);
			System.out.println(new String(packet.getData()));
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}

2.UDP客戶端

package com.icngor.net;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
/**
 * 數據驅動,DatagramPacket,地址和端口存放在數據中
 * @author Administrator
 *
 */
public class UDPClient {
public static void main(String[] args) {

	try {
		DatagramSocket client = new DatagramSocket(7777);//客戶端發送端口
		String data = "icngor";
		DatagramPacket p = new DatagramPacket(data.getBytes(), data.getBytes().length,new InetSocketAddress("localhost",8888));
		client.send(p);

		client.close();

	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

}

}

2.TCP編程

1.TCP服務端

package com.icngor.net;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {

	public static void main(String[] args) throws IOException {
		ServerSocket server = new ServerSocket(8888);
		Socket socket = server.accept();
		System.out.println("success");

		DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
		dos.write("你好\r\n".getBytes());
		dos.flush();
	}

}

2.TCP客戶端

package com.icngor.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;

public class TCPClient {

	public static void main(String[] args) throws UnknownHostException, IOException {
		Socket client =new Socket("localhost", 8888);
		//DataInputStream dis =new DataInputStream(client.getInputStream());
		BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream(), "utf-8"));
		System.out.println(new String(br.readLine()));
	}

}
相關文章
相關標籤/搜索