Java TCP编程练习:键盘输入

一:
package cn.tx.demo1.demo2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPServer {
public static void main(String[] args) {
ServerSocket ss = null;
Socket s = null;
BufferedReader reader = null;
//创建服务器套接字
try {
ss = new ServerSocket(10000);
System.out.println(“服务器已经启动了…”);
//接收客户端的请求:accept接受
//Socket accept = ss.accept();
s = ss.accept();
//获得流的对象:InputStream输入流
InputStream in = s.getInputStream();
//BufferedReader缓冲区读取 Reader:阅读器,InputStreamReader字符流
reader = new BufferedReader(new InputStreamReader(in));
while (true){
//读取数据:readLine读取一行
String line = reader.readLine();
//获得地址getInetAddress
InetAddress address = s.getInetAddress();
//getHostAddress获得主机地址
String ip = address.getHostAddress();
System.out.println(ip+“发送了:”+line);
}

    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {//处理异常快捷键ctrl+alt+t
            if (reader != null){
                reader.close();
            }
            if (s != null){
                s.close();
            }
            if (ss != null){
                ss.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

}
二:
package cn.tx.demo1.demo2;

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

public class TCPClient {
public static void main(String[] args) {
// 创建套接字Socket 处理异常
Socket s = null;
BufferedWriter writer = null;//BufferedWriter缓冲区输出,用字符流方便些
BufferedReader reader = null;//BufferedReader缓冲区读取
try {
s = new Socket(“127.0.0.1”,10000);
//获得输出流
OutputStream out = s.getOutputStream();
//OutputStreamWriter 是字符流通向字节流的桥梁;输出流
writer = new BufferedWriter(new OutputStreamWriter(out));
//InputStreamReader输入流
reader = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while (true){
line = reader.readLine();//readLine逐行读取
//写入数据,writer写入字符流的抽象类;write写入
writer.write(line);// writer.write(“老师好!”);
writer.newLine();//newLine换行
writer.flush();//flush刷新
}

    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            if (s != null){
                s.close();
            }
            if (writer != null){
                writer.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}

}
输入后 记得敲回车,本人老忘。
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值