服务器端:
1 import java.net.*; 2 import java.io.*; 3 public class SocketServer extends Thread { 4 private ServerSocket serverSocket; 5 public SocketServer(int port) throws IOException 6 { 7 serverSocket=new ServerSocket(port); 8 //等待客户连接的时间不超过6秒 9 serverSocket.setSoTimeout(100000); 10 } 11 public void run() 12 { 13 while(true) 14 { 15 try 16 { 17 System.out.println("等待远程连接,端口号为:"+serverSocket.getLocalPort()); 18 Socket server =serverSocket.accept(); 19 System.out.println("远程主机地址"+server.getRemoteSocketAddress()); 20 //从客户端读数据 21 DataInputStream in=new DataInputStream(server.getInputStream()); 22 System.out.println(in.readUTF()); 23 //往客户端发送数据 24 DataOutputStream out=new DataOutputStream(server.getOutputStream()); 25 out.writeUTF("谢谢连接我:"+server.getLocalSocketAddress()+"\nGoodbye!"); 26 server.close(); 27 } 28 catch(SocketException s) 29 { 30 System.out.println("Socket timed out"); 31 break; 32 } 33 catch(IOException e) 34 { 35 e.printStackTrace(); 36 break; 37 } 38 } 39 } 40 public static void main(String[] args) 41 { 42 int port=6066; 43 try 44 { 45 Thread t=new SocketServer(port); 46 t.run(); 47 } 48 catch(IOException e) 49 { 50 e.printStackTrace(); 51 } 52 } 53 }
客户端:
1 import java.net.*; 2 import java.io.*; 3 public class SocketClient { 4 public static void main(String[] args) 5 { 6 //服务器地址 7 String serverName="localhost"; 8 //服务器端口号 9 int port=6066; 10 try 11 { 12 System.out.println("连接到主机:"+serverName+",端口号:"+port); 13 Socket client=new Socket(serverName,port); 14 System.out.println("远程主机地址:"+client.getRemoteSocketAddress()); 15 //向服务器传送消息 16 OutputStream outToServer=client.getOutputStream(); 17 DataOutputStream out=new DataOutputStream(outToServer); 18 out.writeUTF("Hello from"+client.getLocalSocketAddress()); 19 20 //获取服务器返回的信息 21 InputStream inFromServer=client.getInputStream(); 22 DataInputStream in=new DataInputStream(inFromServer); 23 System.out.println("服务器响应:"+in.readUTF()); 24 client.close(); 25 } 26 catch(IOException e) 27 { 28 e.printStackTrace(); 29 } 30 } 31 32 }