45fan.com - 路饭网

搜索: 您的位置主页 > 电脑频道 > 电脑教程 > 阅读资讯:如何使用java写一个能接收二进制流的sokect服务端?

如何使用java写一个能接收二进制流的sokect服务端?

2016-09-05 11:16:36 来源:www.45fan.com 【

如何使用java写一个能接收二进制流的sokect服务端?

Server source code
---------------------------------------------------------------------------------------------------------------------
// SecureHelloServer.java

import java.net.*;
import java.io.*;
import java.util.*;
import java.lang.*;

import javax.net.*;
import javax.net.ssl.*;

import javax.security.cert.X509Certificate;
import oracle.security.ssl.OracleSSLServerSocketFactoryImpl;
import oracle.security.ssl.OracleSSLServerSocketFactory;
import oracle.security.ssl.OracleSSLProtocolVersion;
import oracle.security.ssl.OracleSSLCredential;


public class SecureHelloServer
{

private static byte[] getBytesFromFile(File file) throws
IOException {
InputStream is = new FileInputStream(file);

// Get the size of the file
long length = file.length();

// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
}

// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];

// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}

// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file
"+file.getName());
}

// Close the input stream and return bytes
is.close();
return bytes;
}

public static void main(String[] args)
{
// We will use Oracle implementation here
java.util.Properties prop = System.getProperties();
prop.put("SSLServerSocketFactoryImplClass",

"oracle.security.ssl.OracleSSLServerSocketFactoryImpl");
try
{
// Get the default socket factory
OracleSSLServerSocketFactory sslSrvSocketFactory
=
(OracleSSLServerSocketFactory)SSLServerSocketFactory.getDefault();

// Set the SSL protocol version

sslSrvSocketFactory.setSSLProtocolVersion(OracleSSLProtocolVersion.SSL_Version_3_0);

// Create the ssl credential object
OracleSSLCredential sslCredObj = new
OracleSSLCredential();

sslCredObj.addTrustedCert(getBytesFromFile(new
File("C://certificate//serverTrust")));

// If you are using Oracle's wallet, certdb.txt, you
can use setWallet as follows:
//sslCredObj.setWallet("C://certificate//certdb.txt",
"servicedesk123");

// If you are not using Oracle Wallet Manager, see the
SecureHelloClient
// program example.

// Add ssl credential to the ssl context
sslSrvSocketFactory.setSSLCredentials(sslCredObj);

// Create the server socket
SSLServerSocket sslSrvSocket =

(SSLServerSocket)sslSrvSocketFactory.createServerSocket(8443);

// Print the available ciphers
String [] ciphers =
sslSrvSocket.getSupportedCipherSuites() ;

// Select the ciphers you want and put it.
// Here we will put all available ciphers.
// You can also set particular cipher suite.
// Construct a cipher list and in a string array and
// pass it to setEnabledCipherSuites.
sslSrvSocket.setEnabledCipherSuites(ciphers);

// We are creating ssl server socket, so set the mode
to false.
sslSrvSocket.setUseClientMode(false);

// If you want do client side authentication then set
it to true.
// We won't do client side authintication here.
sslSrvSocket.setNeedClientAuth(false);


System.out.println("Wating for client...");
// Now accept a client connection
Socket pSocket = sslSrvSocket.accept();

if (sslSrvSocket.getNeedClientAuth() == true)
{
System.out.println("Printing client
information:");
X509Certificate[] peerCerts
=

((javax.net.ssl.SSLSocket)pSocket).getSession().getPeerCertificateChain();

if (peerCerts != null)
{
for(int i =0; i < peerCerts.length; i++)
{
System.out.println("Peer Certificate
["+i+"] Information:");
System.out.println("- Subject: " +
peerCerts[i].getSubjectDN().getName());
System.out.println("- Issuer: " +
peerCerts[i].getIssuerDN().getName());
System.out.println("- Version: " +
peerCerts[i].getVersion());
System.out.println("- Start Time: " +
peerCerts[i].getNotBefore().toString());
System.out.println("- End Time: " +
peerCerts[i].getNotAfter().toString());
System.out.println("- Signature
Algorithm: " +
peerCerts[i].getSigAlgName());
System.out.println("- Serial Number: " +
peerCerts[i].getSerialNumber());

}
}
else
System.out.println("Failed to get peer
certificates");
}

// Now do data exchange with client
OutputStream out = pSocket.getOutputStream();
InputStream in = pSocket.getInputStream();

String inputLine, outputLine;
byte [] msg = new byte[1024];

int readLen = in.read(msg, 0, msg.length);
if(readLen>0)
{
inputLine = new String(msg, 0, readLen);
if(inputLine.startsWith("HELLO"))
{
outputLine = "Hello !! Current Server Time: "
+ new Date().toString();
outputLine.getBytes();
out.write(outputLine.getBytes());
}
System.out.println("Client Message: " + inputLine
);
}
else
System.out.println("Can't read data from client");

// Close all sockets and streams
out.close();
in.close();
pSocket.close();
sslSrvSocket.close();
}
catch(SSLException e)
{
System.out.println("SSL exception caught:");
e.printStackTrace();
}
catch(IOException e)
{
System.out.println("IO exception caught:");
e.printStackTrace();
}
catch(Exception e)
{
System.out.println("Exception caught:");
e.printStackTrace();
}
}
}

---------------------------------------------------------------------------------------------------------------------
Client source code
---------------------------------------------------------------------------------------------------------------------
// SecureHelloClient.java
import java.net.*;
import java.io.*;
import java.util.*;

import javax.net.ssl.*;

import javax.security.cert.X509Certificate;
import oracle.security.ssl.OracleSSLCredential;
import oracle.security.ssl.OracleSSLSocketFactory;
import oracle.security.ssl.OracleSSLProtocolVersion;
import oracle.security.ssl.OracleSSLSession;

public class SecureHelloClient
{
public static void main(String argv[])
{
String hostName = "localhost";

//if(argv.length != 0)
// String hostName = argv[0];

// Set the SSLSocketFactoryImpl class as follows:
java.util.Properties prop = System.getProperties();
prop.put("SSLSocketFactoryImplClass",
"oracle.security.ssl.OracleSSLSocketFactoryImpl");

try
{
// Get the default socket factory
OracleSSLSocketFactory sSocFactory
=
(OracleSSLSocketFactory)SSLSocketFactory.getDefault();


sSocFactory.setSSLProtocolVersion(OracleSSLProtocolVersion.SSL_Version_3_0);

OracleSSLCredential sslCredObj = new
OracleSSLCredential();

// Set the certificate chain and private key if the
// server requires client authentication
//sslCredObj.addCertChain(caCert)
//sslCredObj.addCertchain(userCert)
//sslCredObj.setPrivateKey(userPvtKey, userPassword)

// Populate credential object
//sslCredObj.addTrustedCert(trustedCert);
sSocFactory.setSSLCredentials(sslCredObj);

// Create the socket using factory
SSLSocket jsslSoc =
(SSLSocket)sSocFactory.createSocket(hostName,
8443);

String [] ciphers = jsslSoc.getSupportedCipherSuites()
;

// Select the ciphers you want and put them.
// Here we will put all availabel ciphers
jsslSoc.setEnabledCipherSuites(ciphers);

// We are creating socket in client mode
jsslSoc.setUseClientMode(true);

// Do SSL handshake
jsslSoc.startHandshake();

// Print negotiated cipher
System.out.println("Negotiated Cipher Suite: "
+jsslSoc.getSession().getCipherSuite());

System.out.println("");
X509Certificate[] peerCerts
=
((javax.net.ssl.SSLSocket)jsslSoc).getSession().getPeerCertificateChain();

if (peerCerts != null)
{
System.out.println("Printing server
information:");
for(int i =0; i < peerCerts.length; i++)
{
System.out.println("Peer Certificate
["+i+"] Information:");
System.out.println("- Subject: " +
peerCerts[i].getSubjectDN().getName());
System.out.println("- Issuer: " +
peerCerts[i].getIssuerDN().getName());
System.out.println("- Version: " +
peerCerts[i].getVersion());
System.out.println("- Start Time: " +
peerCerts[i].getNotBefore().toString());
System.out.println("- End Time: " +
peerCerts[i].getNotAfter().toString());
System.out.println("- Signature Algorithm: "
+ peerCerts[i].getSigAlgName());

System.out.println("- Serial Number: " +
peerCerts[i].getSerialNumber());
}
}
else
System.out.println("Failed to get peer
certificates");

// Now do data exchange with client
OutputStream out = jsslSoc.getOutputStream();
InputStream in = jsslSoc.getInputStream();

String inputLine, outputLine;
byte [] msg = new byte[1024];

outputLine = "HELLO";
out.write(outputLine.getBytes());
int readLen = in.read(msg, 0, msg.length);
if(readLen > 0)
{
inputLine = new String(msg, 0, readLen);
System.out.println("");
System.out.println("Server Message:");
System.out.println(inputLine );
}
else
System.out.println("Can't read data from client");

// Close all sockets and streams
out.close();
in.close();
jsslSoc.close();
}
catch(SSLException e)
{
System.out.println("SSL exception caught:");
e.printStackTrace();
}
catch(IOException e)
{
System.out.println("IO exception caught:");
e.printStackTrace();
}
catch(Exception e)
{
System.out.println("Exception caught:");
e.printStackTrace();
}
}
}

 

本文地址:http://www.45fan.com/dnjc/72643.html
Tags: 一个 Java 二进制
编辑:路饭网
关于我们 | 联系我们 | 友情链接 | 网站地图 | Sitemap | App | 返回顶部