现在的位置: 首页 > 综合 > 正文

java网络编程【2】 基于Socket的java网络编程(含实例)

2013年02月06日 ⁄ 综合 ⁄ 共 3794字 ⁄ 字号 评论关闭

1,什么是Socket

网络上的两个程序通过一个双向的通讯连接实现数据的交换,这个双向链路的一端称为一个Socket。Socket通常用来实现客户方和服务方的连接。Socket是TCP/IP协议的一个十分流行的编程界面,一个Socket由一个IP地址和一个端口号唯一确定。

但是,Socket所支持的协议种类也不光TCP/IP一种,因此两者之间是没有必然联系的。在Java环境下,Socket编程主要是指基于TCP/IP协议的网络编程。

2,Socket通讯的过程

       Server端Listen(监听)某个端口是否有连接请求,Client端向Server 端发出Connect(连接)请求,Server端向Client端发回Accept(接受)消息。一个连接就建立起来了。Server端和Client 端都可以通过Send,Write等方法与对方通信。

对于一个功能齐全的Socket,都要包含以下基本结构,其工作过程包含以下四个基本的步骤:

  (1) 创建Socket;

  (2) 打开连接到Socket的输入/出流;

  (3) 按照一定的协议对Socket进行读/写操作;

  (4) 关闭Socket.(在实际应用中,并未使用到显示的close,虽然很多文章都推荐如此,不过在我的程序中,可能因为程序本身比较简单,要求不高,所以并未造成什么影响。)

3,创建Socket

    创建Socket

      java在包java.net中提供了两个类Socket和ServerSocket,分别用来表示双向连接的客户端和服务端。这是两个封装得非常好的类,使用很方便。其构造方法如下:

  Socket(InetAddress address, int port);

  Socket(InetAddress address, int port, boolean stream);

  Socket(String host, int prot);

  Socket(String host, int prot, boolean stream);

  Socket(SocketImpl impl)

  Socket(String host, int port, InetAddress localAddr, int localPort)

  Socket(InetAddress address, int port, InetAddress localAddr, int localPort)

  ServerSocket(int port);

  ServerSocket(int port, int backlog);

  ServerSocket(int port, int backlog, InetAddress bindAddr)

  其中address、host和port分别是双向连接中另一方的IP地址、主机名和端 口号,stream指明socket是流socket还是数据报socket,localPort表示本地主机的端口号,localAddr和 bindAddr是本地机器的地址(ServerSocket的主机地址),impl是socket的父类,既可以用来创建serverSocket又可 以用来创建Socket。count则表示服务端所能支持的最大连接数。例如:学习视频网 http://www.xxspw.com

  Socket client = new Socket("127.0.01.", 80);

  ServerSocket server = new ServerSocket(80);

  注意,在选择端口时,必须小心。每一个端口提供一种特定的服务,只有给出正确的端口,才 能获得相应的服务。0~1023的端口号为系统所保留,例如http服务的端口号为80,telnet服务的端口号为21,ftp服务的端口号为23, 所以我们在选择端口号时,最好选择一个大于1023的数以防止发生冲突。

  在创建socket时如果发生错误,将产生IOException,在程序中必须对之作出处理。所以在创建Socket或ServerSocket是必须捕获或抛出例外。


几个简单的例子:

【1】

(1)客户端:

public class TestClient {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		try {
			Socket s1 = new Socket("127.0.0.1",8888);
			InputStream is = s1.getInputStream();
			DataInputStream dis = new DataInputStream(is);
			System.out.println(dis.readUTF());
			dis.close();
			s1.close();
		} catch (ConnectException connEx) {
			connEx.printStackTrace();
			System.out.println("服务器连接失败");
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}

}

(2)服务器端:

public class TestServer {

	/**
	 * @param args
	 */
	public static void main(String[] args){
		try {
			ServerSocket ss = new ServerSocket(8888);
			while(true){
				Socket s1 = ss.accept();
				OutputStream os = s1.getOutputStream();
				DataOutputStream dos = new DataOutputStream(os);
				dos.writeUTF("hello" + s1.getInetAddress() + "port#" + s1.getPort() + "bye-bye");
				dos.close();
				s1.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("程序出错:" + e);
		}
		
		

	}

}

首先 运行 服务器端,在运行客户端:结果:hello/127.0.0.1port#1869bye-bye


【2】

(1)服务器端

public class TestSocketServer {

	/**
	 * 
	 * 先读后写 。。。
	 * 
	 */
	public static void main(String[] args) {
		InputStream in = null;
		OutputStream out = null;
		try {
			ServerSocket ss = new ServerSocket(3666);
			Socket socket = ss.accept();
			
			in = socket.getInputStream();
			out = socket.getOutputStream();
			
			// 首先写入:
			DataOutputStream dos = new DataOutputStream(out);
			DataInputStream dis = new DataInputStream(in);
			
			String s = null;
			// 从对方那里  不停地读。
			if((s=dis.readUTF())!=null){
				System.out.println(s);
				// 把对方的  IP和端口号 全部打印出来。。。
				System.out.println("from " + socket.getInetAddress());
				System.out.println("Port " + socket.getPort());
			}
			
			dos.writeUTF("hi hello");
			dis.close();
			dos.close();
			socket.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

(2)客户端:

public class TestSocketClient {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		InputStream is = null;
		OutputStream os = null;

		try {
			Socket socket = new Socket("localhost", 3666);
			is = socket.getInputStream();
			os = socket.getOutputStream();

			// 首先 读取。
			DataInputStream dis = new DataInputStream(is);
			DataOutputStream dos = new DataOutputStream(os);

			dos.writeUTF("hey");
			String s = null;
			if ((s = dis.readUTF()) != null)
				;
			System.out.println(s);
			dos.close();
			dis.close();
			socket.close();

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

	}

}


抱歉!评论已关闭.