Rumah  >  Artikel  >  Java  >  Java实现的基于socket通信的实例代码

Java实现的基于socket通信的实例代码

高洛峰
高洛峰asal
2017-01-05 14:20:311389semak imbas

服务器端代码:

import java.io.BufferedReader;
 import java.io.InputStreamReader;
 import java.net.ServerSocket;
 import java.net.Socket;

 public class Server {
     public static void main(String[] args) {
         ServerSocket server;
         try{
             server = new ServerSocket(1111);
             Socket socket = server.accept();

             BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
             System.out.println(br.readLine());
             br.close();
             socket.close();
             server.close();
         }catch (Exception e) {
             System.out.println(e);
         }
     }
 }

客户端代码:

import java.io.BufferedReader;
 import java.io.InputStreamReader;
 import java.io.PrintStream;
 import java.net.Socket;

 public class Client {
     public static void main(String[] args) {
         Socket socket;
         PrintStream ps;
         try {
             socket = new Socket("127.0.0.1",1111);
             System.out.println("connect successfully...");
             System.out.println("Please input some WORDS to server:");
             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
             String content = null;
             try {
                 content = br.readLine();
             } catch (Exception e) {

             }
             ps = new PrintStream(socket.getOutputStream(),true,"UTF-8");
             ps.print(content);

             socket.close();
         } catch (Exception e) {
             System.out.println(e);
         }
     }
 }

更多Java实现的基于socket通信的实例代码相关文章请关注PHP中文网!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn