package com.tz.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
/**
* @author 墨风
* 模拟客户端
*/
public class Client {
public static void main(String[] args) throws IOException{
//1.创建客户端对象
//Socket socket = new Socket("192.168.2.132",8888);
//Socket socket = new Socket("localhost",8888);//localhost表示本机IP
Socket socket = new Socket(InetAddress.getLocalHost(),8888);
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
//将字节流转化为字符流
PrintWriter pw = new PrintWriter(os,true);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Scanner input = new Scanner(System.in);
while(true){
String info = input.nextLine();
//通过流发送信息
pw.println("客户端说:"+info);
String info1 = br.readLine();
System.out.println(info1);
if(info1.endsWith("bye")||info.endsWith("bye")){
break;
}
}
}
}
package com.tz.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
* @author 墨风
* 模拟服务器端
*/
public class Server {
public static void main(String[] args) throws Exception {
//1.创建对象
ServerSocket ss = new ServerSocket(8888);
//2.开启服务器监听
Socket s = ss.accept();
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
PrintWriter pw = new PrintWriter(os,true);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
Scanner input = new Scanner(System.in);
while(true){
String info = br.readLine();
System.out.println(info);
String info1 = input.nextLine();
pw.println("服务器说:"+info1);
if(info1.endsWith("bye")||info.endsWith("bye")){
break;
}
}
}
}
我有几点不懂:
为什么要使用超类只是为了转换时传参?
客户端中的nextLine()此扫描器执行当前行,并返回跳过的输入信息。不太懂啥意思
客户端中的这个
if(info1.endsWith("bye")||info.endsWith("bye")){break;}啥意思
客户端和服务器就通过socket通信?他们的代码是靠什么关联的比如父类与子类他们有个extends
可以简要说下这个原理吗?
跪求大神
慕沐9307871
相关分类