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网络练习一的主要内容,如果未能解决你的问题,请参考以下文章

练习30--else和if

java练习题(字符串类):显示4位验证码输出年月日从XML中抓取信息

JAVA坦克大战项目练习日4

2019.7.7 练习题

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

动态SQL基础概念复习(Javaweb作业5)