服务端
package com.java520.tcpandudp;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws Exception {
String data = "hello,my friend,how are you";
//创建服务端,指定端口为8888
ServerSocket server = new ServerSocket(8888);
System.out.println("服务端已经准备就绪");
//接收连接该服务端的客户端对象
boolean accpet = true;
while(accpet){
Socket client = server.accept();
System.out.println("连接过来的客户端:"+client.getInetAddress());
//获取该客户端的输出流对象,给客户端输出数据
PrintStream out = new PrintStream(client.getOutputStream());
out.println(data);
out.close();
}
server.close();
}
}
客户端
package com.java520.tcpandudp;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
//创建客户端对象,并指明连接服务端的主机和端口
Socket client = new Socket("localhost", 8888);
//获取客户端的输入流对象
Scanner sc = new Scanner(client.getInputStream());
while(sc.hasNextLine()){
String line = sc.nextLine();
System.out.println(line);
}
sc.close();
client.close();
}
}