码迷,mamicode.com
首页 > 编程语言 > 详细

Java如何在指定端口创建套接字?

时间:2018-09-10 11:06:47      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:etl   res   err   sock   opera   known   .net   catch   func   

在Java编程中,如何在指定端口创建套接字并连接到指定服务器的端口?

下面的例子演示了Socket类的Socket构造函数,并且使用getLocalPort(),getLocalAddress()getInetAddress()以及getPort()方法获取Socket细节。

package com.yiibai;

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

public class CreateSocket {
    public static void main(String[] args) {
        try {
            InetAddress addr = InetAddress.getByName("112.124.103.85");
            Socket theSocket = new Socket(addr, 80);
            System.out.println("Connected to " + theSocket.getInetAddress() + " on port " + theSocket.getPort()
                    + " from port " + theSocket.getLocalPort() + " of " + theSocket.getLocalAddress());
        } catch (UnknownHostException e) {
            System.err.println("I can‘t find " + e);
        } catch (SocketException e) {
            System.err.println("Could not connect to " + e);
        } catch (IOException e) {
            System.err.println(e);
        }
    }
}
Java

上述代码示例将产生以下结果 -

Connected to /112.124.103.85 on port 80 from port 57229 of /192.168.1.50

Java如何在指定端口创建套接字?

标签:etl   res   err   sock   opera   known   .net   catch   func   

原文地址:https://www.cnblogs.com/borter/p/9617179.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!