Socket通信1.0
服务器端:
package page;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class Server {
public static void main(String[] args) throws UnknownHostException {
Socket socket = null;
ServerSocket serverSocket=null;
try {
while(true){
serverSocket= new ServerSocket(4242);//创建绑定端口8000的对象ServerSocket
System.out.println("服务器已经启动");
socket = serverSocket.accept();//接收客户端请求,得到Socket
System.out.println("有客户端连接过来了");
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));//创建带缓冲的字符读入流
String sr = br.readLine();//读取一个文本行
PrintStream ps = new PrintStream(socket.getOutputStream());//此输出流不会抛出异常
ps.println(new StringBuffer(sr).reverse());//将反转后的字符串打印到客户端屏幕上
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(socket != null)
socket.close();
if(serverSocket != null)
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
客户端:
package page;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class Client {
public static void main(String[] args){
Socket socket = null;
try {
socket = new Socket("localhost",4242);//创建Socket, 请求服务端
System.out.println("客户端已经连接上");
while(true){
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
Scanner scanner = new Scanner(System.in); // 创建Scanner
System.out.println("请输入一个字符串6:"); // 给出提示输入
String line = scanner.nextLine(); // 从键盘输入读取一行
ps.println(line);//发送到服务端
ps.flush();
if((socket.getInputStream().available())==0)
System.out.println(br.readLine());// 读取服务端发回的字符串, 打印
}
} catch (Exception e){
e.printStackTrace();
}finally{
if(socket != null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}