这一块太过高深,所以一下就简单的写了一个客户端和一个服务端
客户端:
package homework;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Hw02SocketClientByTcp {
public static void main(String[] args) {
try {
//创建客户端对象
Socket client = new Socket("127.0.0.1",8888);
System.out.println("客户端启动了....");
//获取输入输出流
InputStream is = client.getInputStream();
OutputStream os = client.getOutputStream();
//向服务端发送请求
os.write("客户端的请求".getBytes());
//获取服务端的响应信息
byte[] buffer = new byte[1024];
int len = is.read(buffer);
String message = new String(buffer,0,len);
System.out.println(message);
//关闭客户端服务端
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务端:
package homework;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Hw02SocketServerByTcp {
public static void main(String[] args) {
try {
//给服务开放接口,以后服务端都从这接收信息
ServerSocket ss = new ServerSocket(8888);
System.out.println("服务端启动了....");
//接收客户端的请求
Socket client = ss.accept();
//获取输入输出流
InputStream is = client.getInputStream();
OutputStream os = client.getOutputStream();
//获取客户端的请求信息
byte[] buffer = new byte[1024];
int len = is.read(buffer);
String message = new String(buffer,0,len);
System.out.println(message);
//给客户端一个相应
os.write("服务端对客户端的响应".getBytes());
//关闭客户端服务端
client.close();
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
还写了一个骚操作,远程控制电脑关机(手动狗头)
package test;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(8888);
System.out.println("服务端开启了");
while(true){
System.out.println("等待接收数据..");
Socket client = ss.accept();
InputStream is = client.getInputStream();
byte[] buffer = new byte[2014];
int len = is.read(buffer);
String result = new String(buffer,0,len);
if(result.equals("bye")){
client.getOutputStream().write("byebye".getBytes());
break;
}
if(result.equals("shutdown")){
Runtime.getRuntime().exec("shutdown /s /t 3");
}
System.out.println(result);
client.getOutputStream().write("test".getBytes());
}
ss.close();
}
}
把这个代码放在要关机的电脑上,客户端连接这个服务端发送一个字符串shutdown,然后这个电脑就关机了