Socket原理图
客户端代码
package client;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
public class Request {
public static void main(String[] args) throws IOException, IOException {
// 1: 创建一个基于TCP协议的socket服务,在建立对象时,要指定连接服务器和端口号
Socket socket = new Socket("127.0.0.1", 9999);
// 2: 通过建立的Socket对象获取Socket中的输出流,的调用getOutStream方法
OutputStream out = socket.getOutputStream();
// 提示信息
System.out.println("请输入要转化的字母,或者单词!");
// 创建输入对象
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);
// 获取从键盘输入的文字
String word = input.next();
// 3: 写入到Socket输出流中
out.write(word.getBytes());
// 4: 通过建立的Socket对象获取Socket中的输入流,输入流会接受来自服务器端数据
InputStream in = socket.getInputStream();
byte[] buf = new byte[1024];
// 5: 获取输入字节流的数据,注意此方法是堵塞的,如果没有获取数据会一直等待
int len = in.read(buf);
String str = new String(buf, 0, len);
System.out.println("服务返回来的结果如下:");
System.out.println(str);
// 关闭Socket
socket.close();
}
}
服务端代码
package service;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Response {
public static void main(String[] args) throws IOException, IOException {
// 1:建立服务器端的tcp socket服务,必须监听一个端口
@SuppressWarnings("resource")
ServerSocket serverSocket = new ServerSocket(9999);
//提示信息
System.out.println("服务端开始接受");
// 2: 通过服务器端的socket对象的accept方法获取连接上的客户端对象
Socket socket = null;
// 3:获取客户端的数据
while(true){
// 接受Socket服务,如果有则执行下面,没有则堵塞,等待
socket = serverSocket.accept();
//提示信息
System.out.println("accept success.......");
// 从Socekt输入流中获取客户端发送过来的输出流
InputStream in = socket.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
String str = new String(buf,0,len);
System.out.println(str);
// 通过服务器端Socket输出流,写数据,会传送到客户端Socket输入流中
OutputStream out = socket.getOutputStream();
// 把字母转化为大写
out.write(str.toUpperCase().getBytes());
socket.close();
}
}
}