Socket通信

        Socket是支持TCP/IP协议的网络通信的基本操作单元,是对网络通信过程中端点的抽象表示,包含了进行网络通信所必需的5种信息:连接所使用的协议、本地主机的IP地址、本地进程的协议端口、远地主机的IP地址以及远地进程的协议端口。

服务端接收消息 

package com.dome;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server_socket {
    public static final int PORT =8081;

    public static void main(String[] args) throws Exception{
        ServerSocket s=new ServerSocket(PORT);
        System.out.println("Started: "+s);
        try {
            Socket socket=s.accept();
            try {
                System.out.println("Connection accepted: "+socket);
                BufferedReader in=new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));
                PrintWriter out =new PrintWriter(new BufferedWriter(
                        new OutputStreamWriter(socket.getOutputStream())),true);
                        while (true){
                            String str= in.readLine();
                            if(str.equals("END")) break;;
                            System.out.println("Echoing:"+str);
                            out.println(str+" haha");
                        }

            }finally {
                System.out.println("closing……");
                socket.close();
            }
        }finally {
            s.close();
        }
    }
}

客户端发送消息 

package com.dome;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class Client_Socket {
    public static void main(String[] args) throws Exception{
        InetAddress address=InetAddress.getByName(null);
        System.out.println("adder="+address);
        Socket socket=new Socket(address,Server_socket.PORT);
        try {
            System.out.println("addr="+address);
            BufferedReader in =new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
            for (int i=0;i<10;i++){
                out.println("www1"+i);
                String str =in.readLine();
                System.out.println(str);
            }
            out.println("END");

        }finally {
            System.out.println("closing……");
            socket.close();
        }
    }
}

多线程请看:Socket多线程通信-CSDN博客

你可能感兴趣的:(java,开发语言)