Socket,网络编程

Socket (ip,port)任何台机两个要连在一起需要 ip和port ( 端口 监听)。
只要port相同。一台机器有几个程序,每个程序需要一个端口,传递接受包。
ServerSocket ( port )服务器打开。
如果Socket s1发出消息,accept ( ) 接受以后创建Socket ss与之对应。
Socket s2 = accept ;
Socket的两个类
InputStream(输入),可以接受输入的情况
OutputStream(输出).可以传输输出的数据

服务器端

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {
    public static int port=3001;
    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(3001);
            System.out.println("在3001上启动服务器");
            while(true){
            Socket socket=ss.accept();
            System.out.println("已经接收");
            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedWriter output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            String clientMsg;
            String serverMsg;
            

            Scanner sc = new Scanner(System.in);
            clientMsg = input.readLine();

            while(!"bye".equals(clientMsg)){
                System.out.println(clientMsg);
                sc.hasNext();
                serverMsg = sc.nextLine();//等待发消息
                output.write(serverMsg+"\r\n");
                output.flush();//发送
                clientMsg = input.readLine();
            }
            sc.close();
            ss.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

客户端

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.Scanner;

public class Client {
public static void main(String[] args) {
    try {
        Socket s=new Socket("localhost",3001);
        BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
        BufferedWriter output = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        String clientMsg;
        String serverMsg;       
        Scanner sc = new Scanner(System.in);
        clientMsg = sc.nextLine();

        while(!"bye".equals(clientMsg)){
            output.write(clientMsg+"\r\n"); //"\r\n"换行
            output.flush();//发送

            serverMsg = input.readLine();//等待发消息
            System.out.println("serverMsg"+serverMsg);//打印消息
            clientMsg = sc.nextLine();
        }

        sc.close();
        s.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

你可能感兴趣的:(Socket,网络编程)