Java网络程序客户端与服务器的连接ServerSocket/Socket

Servesocket是用来表示服务器端的套接字,服务器端套接字通过指定的端口来等待套接字,功能主要是等待客户机端的连接请求。
Socket用来创建客户端套接字,需要指定服务器的ip与端口号,创建Socket对象后会向指定的ip和端口尝试连接。服务器套接字会创建新的套接字,与客户端套接字连接。

  1. socket是端口号与应用程序的连接的一个Java类
  2. ServerSocket一般仅用于设置端口号和监听,socket用于真正的通信是服务端与客户端的socket连接
    客户端与服务端建立连接的例子
    服务器端:
public class Server{
	public static void main(String args[]) {
		ServerSocket serverSocket=null;//创建服务器端套接字
		Socket cliensocket=null;//创建客户机端套接字
		String str=null;
		DataOutputStream out =null;
		DataInputStream in=null;
		try {
			serverSocket=new ServerSocket(4331);
			cliensocket=serverSocket.accept();//接受客户机的套接字连接呼叫
			System.out.println("与客户端建立连接");
			in =new DataInputStream(cliensocket.getInputStream());
			out= new DataOutputStream(cliensocket.getOutputStream());
			while (true) {
				str=in.readUTF();
				out.writeUTF("hello 我是服务器");
				out.writeUTF(str);
				System.out.println("服务器收到:"+str);
				Thread.sleep(1000);//线程休眠
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}

客户端:

public class Client {
	public static void main(String args[]) {
	String str =null;
	Socket clientsocket;
	DataInputStream in =null;
	DataOutputStream out =null;
	try {
		clientsocket=new Socket("127.0.0.1",4331);
		in =new DataInputStream(clientsocket.getInputStream());
		out =new DataOutputStream(clientsocket.getOutputStream());
		out.writeUTF("你好");
		while(true) {
			str=in.readUTF();
			out.writeUTF(((int)(Math.random()*10)+1)+"");
			System.out.println("客户端收到:"+str);
			Thread.sleep(1000);
		}
	}catch(Exception e) {
		e.printStackTrace();
	}
	
}
}

客户端请求服务器端,首先服务器端开始运行,创建特定端口的套接字等待客户端发出的请求,服务器端通过ServerSocket类的accept()方发接受客户端的套接字,返回一个和客户端Socket对象相连接的Socket对象。接受后那么客户端服务器端通过套接字就建立了连接。就可以相互通信了。

你可能感兴趣的:(Java学习)