Java基础(14):网络编程之socket

        socket有两种协议通信方式:分别为tcp和udp。

Tcp协议通信

        tcp协议是一种可靠协议,即使网络暂时阻塞,tcp也能保持通信的可靠性。

        服务端:

public class SocketServerTest {
	
	public void init(){
		
		try {
			
			ServerSocket server=new ServerSocket(1000);
			
			Socket in=server.accept();
			
			InputStream input=in.getInputStream();
			
			OutputStream output=in.getOutputStream();
			
			PrintWriter out=new PrintWriter(output,true); 
			
			out.println("hello , client!");
			
			System.out.println(input);
			
			System.out.println("server start");
			
			out.close();
			
			output.close();
			
			in.close();
			
			server.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

      客服端:

public class SocketClient {
	
	public void init(){
		try {
			
			Socket s=new Socket("127.0.0.1",1000);
			
			InputStream in=s.getInputStream();
			
			BufferedReader br=new BufferedReader(new InputStreamReader(in));
			
			String line=br.readLine();
			
			System.out.println(line);
			
			br.close();
			
			s.close();
			
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

Udp协议通信

      udp协议相对tcp协议是一种不可靠协议,每次传送的数据大小也有限制。

      服务端:

public class UdpServer {
	
	private int SIZE=4096;
	private int PORT=1111;
	private byte []buf=new byte[SIZE];
	private DatagramPacket packet,out;
	public void init() throws IOException{
		try {
			packet=new DatagramPacket(buf, buf.length);
			DatagramSocket socket=new DatagramSocket(PORT);
			socket.receive(packet);
			System.out.println(new String(buf,0,packet.getLength()));
			byte[] data=("server receive").getBytes();
			out=new DatagramPacket(data,data.length,packet.getSocketAddress());
			socket.send(out);
			
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

      客户端

public class UdpClient {

	private int SIZE=4096;
	private String IP="127.0.0.1";
	private int PORT=1111;
	private byte []buf=new byte[SIZE];
	private DatagramPacket packet,out;
	public void init() throws IOException{
		try {
			DatagramSocket socket=new DatagramSocket();
			byte[] outBuf=("client say hello").getBytes();
			packet=new DatagramPacket(buf, buf.length,InetAddress.getByName(IP),PORT);
			out=new DatagramPacket(outBuf, outBuf.length,InetAddress.getByName(IP),PORT);
			socket.send(out);
			socket.receive(packet);
			System.out.println(new String(buf,0,packet.getLength()));
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
}






阅读更多
文章标签: java基础
个人分类: Java
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭