Java简单的socket与socketserver链接
Java 中 socket 与 socketserver 通信及链接很简单,但是数据的相互传输还真是有点东西,不论是输入还是输出。都需要将输入流或者输出流加入到输出缓存区或者输入缓存区才能发送或者接受数据。具体原因暂时说不上来。先做个记录。
服务端:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; public class socketserver { public static void main(String[] args) throws IOException { //。服务端先输入再输出,客户端就先输出再输入。 ServerSocket ss=new ServerSocket(10004); Socket s=ss.accept(); InputStream inputstream = s.getInputStream(); OutputStream outputstream = s.getOutputStream(); InputStreamReader inputStreamReader=new InputStreamReader(inputstream); //。将输入流加入输入流缓冲区 BufferedReader bufferedReader=new BufferedReader(inputStreamReader); //。读取输入流缓冲区数据 String info = bufferedReader.readLine(); System.out.println("接收客户端数据:" + info); //。输出流加入输出流缓冲区 PrintWriter printWriter=new PrintWriter(outputstream); //。输出流缓冲区增加数据 printWriter.print("服务器发送信息:我是服务器"); //。将缓冲区内容刷出去 printWriter.flush(); s.shutdownOutput();//关闭输出流 //。关闭资源 printWriter.close(); outputstream.close(); bufferedReader.close(); inputstream.close(); s.close(); ss.close(); } }
客户端:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; public class socket { public static void main(String[] args) throws UnknownHostException, IOException { //。客户端先输出,再输入。服务端就先输入再输出。 Socket s=new Socket("127.0.0.1", 10004); InputStream inputstream = s.getInputStream(); OutputStream outputstream = s.getOutputStream(); PrintWriter printWriter=new PrintWriter(outputstream); printWriter.print("客户端发送信息:我是客户端"); printWriter.flush(); s.shutdownOutput();//关闭输出流 InputStreamReader inputStreamReader=new InputStreamReader(inputstream); BufferedReader bufferedReader=new BufferedReader(inputStreamReader); String info = bufferedReader.readLine(); System.out.println("接收服务器端数据:" + info); printWriter.close(); outputstream.close(); bufferedReader.close(); inputstream.close(); s.close(); } }
仅仅是个人笔记所用。