JavaSocket简单通信

以下介绍:简单的socket发送消息,服务的Server 相互 客户端Client,进行简单的传递消息:


服务端代码:

package test;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    /**
     * 服务器连接的Socket
     */
    public static ServerSocket cServerSocket;

    /**
     * 连接 
     */
    public static Socket cSocket;

    /**
     * 端口 
     */
    public static final int PORT = 8888;

    public static void main(String[] args) {

        DataInputStream dis = null;
        DataOutputStream dos = null;

        try {
            cServerSocket = new ServerSocket(PORT);
            while (true) {
                System.out.println("正在等待客户连接...");
                // 这里处于等待状态,如果没有客户端连接,程序不会向下执行
                cSocket = cServerSocket.accept();
                dis = new DataInputStream(cSocket.getInputStream());
                dos = new DataOutputStream(cSocket.getOutputStream());
                // 读取数据
                String clientStr = dis.readUTF();

                String msg = "已收到信息:"+clientStr;

                // 写出数据
                dos.writeUTF(msg);

                System.out.println(msg);

                System.out.println("---客户端信息打印,IP:"
                                    + cSocket.getInetAddress()
                                    + " Prot:" + cSocket.getPort());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (dis != null) {
                    dis.close();
                }
                if (dos != null) {
                    dos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

客户端代码:

private Socket cSocket;
// 服务器server/IP地址(当前PC的IP地址)
private final String ADDRESS = "192.168.8.2";
// 服务器端口
private final int PORT = 8888;
cThread = new Thread() {
@Override
public void run() {
    super.run();
    DataInputStream dis = null;
    DataOutputStream dos = null;
    try {
        // 阻塞函数,正常连接后才会向下继续执行
        cSocket = new Socket(ADDRESS, PORT);
        dis = new DataInputStream(cSocket.getInputStream());
        dos = new DataOutputStream(cSocket.getOutputStream());

        // 向服务器写数据
        dos.writeUTF("hello socket...");

        // 读取服务器发来的数据
        cContent += dis.readUTF();

    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (dis != null) {
                dis.close();
            }
            if (dos != null) {
                dos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    };  
    cThread.start();

运行效果:
这里写图片描述


谢谢大家的观看,更多精彩技术博客,会不断的更新,请大家访问,
刘德利CSDN博客, http://blog.csdn.net/u011967006

原文地址:https://www.cnblogs.com/android-deli/p/10322189.html