Java编写一个简单的TCP通信程序。服务器发送一条字符串,客户端接收该信息并显示。

import  java.io.DataOutputStream;
import  java.io.IOException;
import  java.net.ServerSocket;
import  java.net.Socket;
 
public  class  SocketServer {
 
     private  static  final  int  PORT =  8088 ;
 
     public  static  void  main(String[] args) {
         ServerSocket server =  null ;
         try  {
             server =  new  ServerSocket(PORT);
             while  ( true ) {
                 Socket client = server.accept();
                 new  Thread( new  Server(client)).start();
             }
         catch  (IOException e) {
             e.printStackTrace();
         }
     }
 
}
 
class  Server  implements  Runnable {
 
     private  Socket client;
 
     public  Server(Socket client) {
         this .client = client;
     }
 
     public  void  run() {
         DataOutputStream output =  null ;
         try  {
             output =  new  DataOutputStream(client.getOutputStream());
             output.writeUTF( "XXOOXXOOXXOO" );
         catch  (IOException e) {
             e.printStackTrace();
         finally  {
             try  {
                 if  (output !=  null ) output.close();
                 output =  null ;
             catch  (IOException e) {}
         }
     }
 
}

2、客户端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import  java.io.DataInputStream;
import  java.io.IOException;
import  java.net.Socket;
import  java.net.UnknownHostException;
 
public  class  Client  extends  Socket {
 
     private  static  final  int  PORT =  8088 ;
 
     public  static  void  main(String[] args) {
         Socket socket =  null ;
         try  {
             socket =  new  Socket( "127.0.0.1" , PORT);
             DataInputStream in =  new  DataInputStream(socket.getInputStream());
             String res = in.readUTF();
             System.out.println(res);
             if  (in !=  null ) in.close();
         catch  (UnknownHostException e) {
             e.printStackTrace();
         catch  (IOException e) {
             e.printStackTrace();
         finally  {
             if  (socket !=  null ) {
                 try  {
                     socket.close();
                 catch  (IOException e) {}
             }
         }
     }
}

你可能感兴趣的:(SOCKET)