java网络练习一

Posted 卡西莫

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java网络练习一相关的知识,希望对你有一定的参考价值。

package network;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.Socket;
import java.util.Scanner;

public class CliSocketTest {
    public void test(){
        try {
            
            while(true){
                Socket socket = new Socket("192.168.1.2",8888);
                Writer w = new PrintWriter(socket.getOutputStream());
                Scanner scaner = new Scanner(System.in);
                w.write(scaner.nextLine());
                System.out.println("輸入了書");
                w.flush();
                w.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        new CliSocketTest().test();
    }
}
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created by afeng on 2018/3/31.
 */
public class SersocketTest {
    /**
     * 创建服务器socket
     */
    public static void serverSocket() throws IOException {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(8888);
            Socket socket = null;
            while(true){
                socket = serverSocket.accept();
                System.out.println("监听到哦了");
                Scanner scanner = new Scanner(socket.getInputStream());
                while(scanner.hasNextLine()){
                    String msg = scanner.nextLine();
                    System.out.println(socket.getInetAddress()+"說:"+msg);
                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            serverSocket.close();
        }

    }
    public static void main(String[] args) {
        try {
            serverSocket();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

以上是关于java网络练习一的主要内容,如果未能解决你的问题,请参考以下文章

Oracle毙掉JavaOne

JavaOne 2016——观众得以一睹JShell的威力

JavaOne 2016——观众得以一睹JShell的威力

宣布 Java 8 停止维护后,Oracle 又毙掉了 JavaOne

2019.7.7 练习题

新一代企业内部故障报修软件功能实现