【服务器端】
import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class TestServer { public static void main(String[] args) { try { System.out.println("启动服务端"); ServerSocket sv = new ServerSocket(2233); //等待用户链接 Socket socket = sv.accept(); System.out.println("有用户链接!"); while (true) { //1 InputStream is = socket.getInputStream(); //2 byte[] data = new byte[128]; is.read(data,0,data.length); //3 按照格式转成字符串输出 String msg = new String(data, "UTF-8"); //收到的内容 System.out.println("收到的内容:"+ msg); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
【客户机端】
import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; public class TestClient { public static void main(String[] args) { try { Socket socket = new Socket("192.169.191.4", 2244); // Socket socket = new Socket("localhost", 2233); System.out.println("链接服务器成功!"); while (true) { System.out.println("请输入内容:"); //1 Scanner input = new Scanner(System.in); String msg = input.next(); //2 OutputStream os = socket.getOutputStream(); //3 byte[] data = msg.getBytes("UTF-8"); os.write(data); os.flush(); } } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
时间: 2024-11-11 00:12:18