文件名称:java网络编程示例
文件大小:32KB
文件格式:DOC
更新时间:2016-12-30 16:15:27
java
Java 网络编程 说明: 网络编程,分为两种一种是TCP、另一种是UDP方式。我们分别写一下TCP、UDP端的Server和Client简单演示代码。 TCP: Sever import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class TCPServer { public static void main(String[] args) { try { ServerSocket socket = new ServerSocket(4444); while (true) { Socket sc =socket.accept(); InputStream instr = sc.getInputStream(); DataInputStream dataInputStream = new DataInputStream(instr); System.out.println(dataInputStream.readUTF()); } } catch (IOException e) { e.printStackTrace(); } } } Client import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; public class TCPClient { public static void main(String[] args) { try { Socket socket = new Socket("127.0.0.1",4444); OutputStream oStream = socket.getOutputStream(); DataOutputStream dataOutputStream = new DataOutputStream(oStream); dataOutputStream.writeUTF("Hello"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } UDP: Server: 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) { try { byte [] buffer = new byte[1024]; DatagramSocket socket = new DatagramSocket(4444); DatagramPacket packet = new DatagramPacket(buffer, buffer.length); while(true){ socket.receive(packet); System.out.println(new String(buffer,0,packet.getLength())); } } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } Client import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; public class UDPClient { public static void main(String[] args) { byte [] buffer = null; buffer = new String("hello").getBytes(); DatagramPacket packet=null; try { packet = new DatagramPacket(buffer, buffer.length,new InetSocketAddress("127.0.0.1", 4444)); DatagramSocket socket = new DatagramSocket(1234); socket.send(packet); socket.close(); } catch (SocketException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }