java网络编程 Socket 用法举例



Java Socket 用法:

package zrj.java.net.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

public class MySocketTest {
    
    Socket socke = new Socket();
    
    public void setSocke() throws SocketException{
        // 如果 socket 的 InputStream 中
        socke.setSoTimeout(5*1000) ;
    }
    
    public static final int PROT = 13;
    public static void main(String[] args) {
//        if(args.length != 1){
//            System.out.println("地址无效");
//            return ;
//        }
        String hostName = "";
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();
            System.out.println(inetAddress.toString());
            Socket socket = new Socket(inetAddress, PROT); // 创建 套接字
            socket.setSoTimeout(2000);
            System.out.println("连接服务器成功");
            BufferedReader bufreader = new BufferedReader( new InputStreamReader(socket.getInputStream()));
            System.out.println("Reads" + bufreader.readLine().toString());
            socket.close();
            
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            System.out.println("Can not Connection" + e);
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("Error" + e);
        }
    }

}

Java SockeServert用法:

package zrj.java.net.socket;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServerSocket {
	
	Socket socket = null;
	public static final int PORT = 13;
	ServerSocket server;
	public MyServerSocket() {
		try {
			/*
			 * 1:此构造函数的端口号如果指定为 0 则使用任意的 空闲的端口号 但是客户端不能访问服务
			 * 2:默认情况下队列的大小设置  50 个套接字连接
			 * 3:如果端口被绑定, 或者a
			 */
			server = new ServerSocket(PORT);
			System.out.println("服务器IP为" +server.getInetAddress()+"\n服务器启动等待连接\n");
			while(true){
				socket = server.accept();
				System.out.println("客服端IP为"+ socket.getInetAddress().toString());
				//建立输出流
				OutputStream out = socket.getOutputStream();
				//打印流
				PrintWriter pout = new PrintWriter(out);
				//Thread.sleep(5000);
				pout.print(new java.util.Date());
				pout.flush();
				out.close();
				socket.close();
			}
		} catch (IOException e) { // 
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		new MyServerSocket();
	}
}


你可能感兴趣的:(java,编程,socket,网络,String,服务器)