Java中的网络编程

Socket

  • 两个java应用程序可以通过一个双向的网络通信连接实现数据交换,这个双向链路的一段称为一个Socket;
  • Socket通常用来实现client-server连接;
  • Java.net包中定义的两个类Socket和ServerSocket,分别来实现双向连接的client和server端;
  • 建立连接时所需要的寻址信息为远程计算机的IP地址和端口号(Port number)。

TCP Socket通信模型

Java中的网络编程_第1张图片

实例代码:

server端
import java.net.*;
import java.io.*;

public class TestServer{
	public static void main(String[] args){
		try{
			ServerSocket s = new ServerSocket(1111);
			while(true){
				Socket s1 = s.accept();
				OutputStream os = s1.getOutputStream();
				DataOutputStream dos = new DataOutputStream(os);
				dos.writeUTF("Hello,"+s1.getInetAddress()+"prot#"+s1.getPort()+" bye-bye!");
				dos.close();
				s1.close();
			}
		}catch(IOException e){
			e.printStackTrace();
			System.out.println("程序运行出错:" + e);
		}
	}
}

Client端:
import java.net.*;
import java.io.*;

public class TestClient{
	public static void main(String[] args){
		try{
			Socket s1 = new Socket("127.0.0.1",1111);
			InputStream is = s1.getInputStream();
			DataInputStream dis = new DataInputStream(is);
			System.out.println(dis.readUTF());
			dis.close();
			s1.close();
		}catch(ConnectException connExc){
			connExc.printStackTrace();
			System.out.println("服务器连接失败");
		}catch(IOException e){
			e.printStackTrace();
		}
	}
}

采用UDP协议的编码

Server端:
import java.net.*;
import java.io.*;

public class TestUDPServer{
	public static void main(String[] args)throws Exception {
		byte buf[] = new byte[1024];
		DatagramPacket dp = new DatagramPacket(buf,buf.length);
		DatagramSocket ds = new DatagramSocket(5678);
		while(true){
			ds.receive(dp);
			ByteArrayInputStream bais = new ByteArrayInputStream(buf);
			DataInputStream dis = new DataInputStream(bais);
			System.out.println(dis.readLong());
		}
	}
}

Client端:
import java.net.*;
import java.io.*;

public class TestUDPClient{
	public static void main(String[] args) throws Exception{
		long n = 10000L;
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(baos);
		dos.writeLong(n);
		byte[] buf = baos.toByteArray();
		System.out.println(buf.length);
		DatagramPacket dp = new DatagramPacket(buf,buf.length,new InetSocketAddress("127.0.0.1",5678));
		DatagramSocket ds = new DatagramSocket(9999);
		ds.send(dp);
		ds.close();
	}
}

 

你可能感兴趣的:(●Java)