Java Socket编程实例

原文链接: http://www.cnblogs.com/linkcode/p/8150752.html

Java Socket编程笔记

(注:需要 Java IO相关的知识)

1.使用 TCP 连接的demo


需要用到 java.net.Socket  和 java.net.ServerSocket ,具体可以查询 API 文档
创建 Sever 类和 Client 类作为 demo

Server类的实现:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 基于TCp的Socket通信,实现用户登录
 * 服务器端
 */
public class Server {
    public static void main(String[] args) {

        try  {
            //创建一个服务器socket,即serversocket,指定绑定的端口,并监听此端口
            ServerSocket serverSocket = new ServerSocket(8888);
            //调用accept()方法开始监听,等待客户端的连接
            System.out.println("***服务器即将启动,等待客户端的连接***");
            Socket socket = serverSocket.accept();
            //获取输入流,并读入客户端的信息
            InputStream in = socket.getInputStream(); //字节输入流
            InputStreamReader inreader = new InputStreamReader(in); //把字节输入流转换为字符流
            BufferedReader br = new BufferedReader(inreader); //为输入流添加缓冲
            String info = null;
            while((info = br.readLine())!=null){
                System.out.println("我是服务器,客户端说:"+info);
    
            }
            socket.shutdownInput();//关闭输入流

            //获取输出流,相应客户端的信息
            OutputStream outputStream = socket.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream);//包装为打印流
            printWriter.write("欢迎您!");
            printWriter.flush(); //刷新缓冲
            socket.shutdownOutput();

            //关闭资源
            printWriter.close();
            outputStream.close();

            br.close();
            inreader.close();
            in.close();
            socket.close();
            serverSocket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Client类的实现:
import java.io.*;
import java.net.Socket;

/**
 * 客户端
 */
public class Client {
    public static void main(String[] args) {
        //创建客户端socket建立连接,指定服务器地址和端口
        try {
            Socket socket = new Socket("127.0.0.1",8888);
            //获取输出流,向服务器端发送信息
            OutputStream outputStream = socket.getOutputStream();//字节输出流
            PrintWriter pw = new PrintWriter(outputStream); //将输出流包装为打印流
            pw.write("用户名:admin;密码:123");
            pw.flush();
            socket.shutdownOutput();

            //获取输入流,读取服务器端的响应
            InputStream inputStream = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String info = null;
            while((info = br.readLine())!=null){
                System.out.println("我是客户端,服务器说:"+info);

            }
            socket.shutdownInput();

            //关闭资源
            br.close();
            inputStream.close();
            pw.close();
            outputStream.close();
            socket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

运行结果:(!!!!要先运行Server端)
Java Socket编程实例_第1张图片

Java Socket编程实例_第2张图片


2.使用 UDP 连接的demo

要用到 DatagramPacket 和 DatagramSocket 
创建 UDPServer 和 UDPClient 类:

UDPSerer:
/**
 * 服务器端的实现
 */

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPServer {
    public static void main(String[] args) {

        try  {
            //服务器端接收来自客户端的数据
            //创建服务器端的DatagramSocket,指定端口
            DatagramSocket socket = new DatagramSocket(8800);
            //创建数据报,用于接收客户端发送的信息
            byte[] data = new byte[1024];//创建字节数组,指定接收的数据包的大小
            DatagramPacket packet = new DatagramPacket(data,data.length);
            //接收客户端发送的数据
            socket.receive(packet); //接收到数据包之前会一直阻塞,会把数据存入packet的data
            //读取数据
            String info = new String(data,0,packet.getLength());  //读取数据
            System.out.println("I am Server,Client say:"+info);


            //接收到数据后,服务器端响应给客户端,基本与client的发送相同
            //定义客户端的ip地址,端口号,数据
            InetAddress address = packet.getAddress();
            int port = packet.getPort(); //port难道不应该肯定是8800???
            byte[] data2 = "Welcome".getBytes();
            DatagramPacket packet1 = new DatagramPacket(data2,data2.length,address,port);
            socket.send(packet1);

            socket.close();//关闭资源

        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

UDPClient:
import java.io.IOException;
import java.net.*;

/**
 * 客户端实现
 */
public class UDPClient {
    public static void main(String[] args) {

        try {

            //定义服务器的ip,端口号,数据
            InetAddress inetAddress = InetAddress.getByName("localhost");
            int port = 8800;
            byte[] data = "用户名:admin;密码:123".getBytes();
            //创建数据包,包含要发送的信息
            DatagramPacket packet = new DatagramPacket(data,data.length,inetAddress,port);
            //创建datagramsocket
            DatagramSocket socket = new DatagramSocket();
            //使用socket向服务器端发送数据包
            socket.send(packet);
            //socket.close();


            //接收服务器端的响应,基本与Server的接收相同
            byte[] dataR = new byte[1024]; //创建数据包用于接收服务器端的响应
            DatagramPacket packet1 = new DatagramPacket(dataR,dataR.length);
            socket.receive(packet1); //接收响应的数据
            String info = new String(dataR,0,packet1.getLength());  //读取数据
            System.out.println("I am Client,Sever reply:"+info);

            socket.close();//关闭资源





        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


运行结果:(先Server!)

Java Socket编程实例_第3张图片
Java Socket编程实例_第4张图片



转载于:https://www.cnblogs.com/linkcode/p/8150752.html

你可能感兴趣的:(Java Socket编程实例)