如何在Java中按需创建套接字?

时间:2016-02-11 16:31:56

标签: java multithreading sockets serversocket

我正在用Java编写客户端聊天应用程序,我想知道如何按需创建套接字。更具体地说,我想知道是否有任何方法可以检查是否存在传入连接。使用它我可以有两个方法与Threads同时运行,一个方法等待连接,而另一个方法处理服务器(正在发送的消息)。这是一个很好的策略还是应该使用不同的技术?

如果我使用套接字阵列并为每个连接添加一个新的套接字怎么办? 但是,稍后在引用套接字时,阵列是否会引起问题? if有&&什么都没有,因为我想在那里添加一个方法来帮助我检查是否有传入连接。

import java.util.*;
import java.io.*;
import java.net.*;
public class Server {
public static ServerSocket SSock;
public static Socket Sock;
public static DataInputStream dis;
public static DataOutputStream dos;
public static PrintWriter pw;
public static BufferedReader br;
public static Socket[] wow;
public int counter = 0;
public int port = 2500;
public Scanner input = new Scanner(System.in);  

public static void main(String[] args) throws IOException{
    SSock = new ServerSocket();
    Sock = SSock.accept();
    dis = new DataInputStream(Sock.getInputStream());
    dos = new DataOutputStream(Sock.getOutputStream());
    pw = new PrintWriter(dos, true);
    br = new BufferedReader(new InputStreamReader(dis));
    Server s = new Server();
    Thread t1 = new Thread(s.new connection());
    Thread t2 = new Thread(s.new server());
    t1.start();
    t2.start();
}

public class connection implements Runnable {
    public void run() {
        try {
            Thread.sleep(200);
        } catch (Exception e) {
            //NOTHING!! MWAH MWAH MWAH
            //Sigh. I'll add something here later...
        }

        if (  && Sock.isConnected()) {

        }

    }
}

public class server implements Runnable{
    public void run() {

    }
}

}

2 个答案:

答案 0 :(得分:1)

我认为你在某种程度上误解了TCP套接字的概念。当您尝试启动与远程服务器的连接时,它不会“创建需求;”服务器 在发出请求之前侦听套接字,否则您将只会得到“拒绝连接”错误。

在Java中,ServerSocket.accept()为您处理所有这些:它侦听传入的连接,并且一旦建立连接,它就会返回您用于所有进一步通信的Socket特别的联系。

答案 1 :(得分:0)

我想通了,我必须创建一个返回套接字的方法。

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:security="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd"
    default-init-method="init">

    <security:authentication-manager alias="authenticationManager">
        <security:authentication-provider
            user-service-ref="userDetailService">
        </security:authentication-provider>
    </security:authentication-manager>

    <alias name="filterChainProxy" alias="springSecurityFilterChain" />

    <bean id="accessDecisionManager"
        class="org.springframework.security.access.vote.AffirmativeBased">
        <property name="decisionVoters">
            <list>
                <bean class="org.springframework.security.access.vote.RoleVoter" />
                <bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
            </list>
        </property>
    </bean>

    <bean id="consoleAuthenticationSuccessHandler"
        class="custom_class">
        <property name="defaultTargetUrl" value="/loginSuccess.htm" />
        <property name="targetUrlParameter" value="targetURL" />
    </bean>

    <bean id="consoleAuthenticationFailureHandler"
        class="custom_class">
        <property name="loginFailureUrl" value="/loginFailure.htm" />
    </bean>

    <bean id="consoleLogoutSuccessHandler"
        class="custom_class">
        <property name="logoutUrl" value="/loggedout.htm" />
    </bean>

    <bean id="userDetailService"
        class="custom_class">
    </bean>

    <security:http auto-config="true"
        security-context-repository-ref="securityContextRepository">
        <security:form-login authentication-failure-url="/loginFailure.htm"
            default-target-url="/loginSuccess.htm"
            authentication-success-handler-ref="consoleAuthenticationSuccessHandler" />
        <security:logout success-handler-ref="consoleLogoutSuccessHandler" />
        <security:anonymous enabled="false" />
        <security:session-management
            session-fixation-protection="none" />
    </security:http>

    <bean id="filterChainProxy" class="org.springframework.security.web.FilterChainProxy">
        <security:filter-chain-map path-type="ant">
            <security:filter-chain pattern="/login.htm*"
                filters="none" />
            <security:filter-chain pattern="/**"
                filters="securityContextFilter, logoutFilter, formLoginFilter, servletApiFilter, exceptionTranslator, filterSecurityInterceptor" />
        </security:filter-chain-map>
    </bean>

    <bean id="securityContextRepository"
        class="org.springframework.security.web.context.HttpSessionSecurityContextRepository" />

    <bean id="securityContextFilter"
        class="org.springframework.security.web.context.SecurityContextPersistenceFilter">
        <property name="securityContextRepository" ref="securityContextRepository" />
    </bean>
    <bean id="logoutFilter"
        class="org.springframework.security.web.authentication.logout.LogoutFilter">
        <constructor-arg ref="consoleLogoutSuccessHandler"
            index="0"
            type="org.springframework.security.web.authentication.logout.LogoutSuccessHandler" />
        <constructor-arg>
            <list>
                <bean
                    class="org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler" />
            </list>
        </constructor-arg>
    </bean>

    <bean id="servletApiFilter"
        class="org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter" />

    <bean id="exceptionTranslator"
        class="org.springframework.security.web.access.ExceptionTranslationFilter">
        <property name="authenticationEntryPoint">
            <bean
                class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
                <property name="loginFormUrl" value="/login.jsp" />
            </bean>
        </property>
    </bean>

    <bean id="formLoginFilter"
        class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
        <property name="authenticationManager" ref="authenticationManager" />
        <property name="authenticationSuccessHandler" ref="consoleAuthenticationSuccessHandler" />
        <property name="authenticationFailureHandler" ref="consoleAuthenticationFailureHandler" />
    </bean>

    <bean id="filterSecurityInterceptor"
        class="org.springframework.security.web.access.intercept.FilterSecurityInterceptor">
        <property name="securityMetadataSource">
            <security:filter-security-metadata-source>
                <security:intercept-url pattern="/login.htm*"
                    access="ROLE_ANONYMOUS" />
                <security:intercept-url pattern="/**"
                    access="ROLE_USER,ROLE_ADMIN" />
            </security:filter-security-metadata-source>
        </property>
        <property name="accessDecisionManager" ref="accessDecisionManager" />
        <property name="authenticationManager" ref="authenticationManager" />
    </bean>

</beans>