下面列出了怎么用java.net.Socket的API类实例代码及写法,或者点击链接到github查看源代码。
public SocketClient(String commod, onServiceSend onServiceSend) {
cmd = commod;
mOnServiceSend = onServiceSend;
try {
Log.d(TAG, "与service进行socket通讯,地址=" + HOST + ":" + port);
/** 创建Socket*/
// 创建一个流套接字并将其连接到指定 IP 地址的指定端口号(本处是本机)
Socket socket = new Socket();
socket.connect(new InetSocketAddress(HOST, port), 3000);//设置连接请求超时时间3 s
// 接收3s超时
socket.setSoTimeout(3000);
Log.d(TAG, "与service进行socket通讯,超时为:" + 3000);
/** 发送客户端准备传输的信息 */
// 由Socket对象得到输出流,并构造PrintWriter对象
printWriter = new PrintWriter(socket.getOutputStream(), true);
/** 用于获取服务端传输来的信息 */
// 由Socket对象得到输入流,并构造相应的BufferedReader对象
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
new CreateServerThread(socket);
send(cmd);
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "与service进行socket通讯发生错误" + e);
mOnServiceSend.getSend("###ShellRunError:" + e.toString());
}
}
private Runnable createConnectionTask(Socket connection) {
return new Runnable() {
@Override
public void run() {
try {
ProtocolServer protocolServer = new ProtocolServer(connection.getInputStream(), connection.getOutputStream(),
JdtProviderContextFactory.createProviderContext());
// protocol server will dispatch request and send response in a while-loop.
protocolServer.run();
} catch (IOException e) {
logger.log(Level.SEVERE, String.format("Socket connection exception: %s", e.toString()), e);
} finally {
logger.info("Debug connection closed");
}
}
};
}
private boolean replaceBlock( Block block, DatanodeInfo source,
DatanodeInfo sourceProxy, DatanodeInfo destination, int namespaceId) throws IOException {
Socket sock = new Socket();
sock.connect(NetUtils.createSocketAddr(
destination.getName()), HdfsConstants.READ_TIMEOUT);
sock.setKeepAlive(true);
// sendRequest
DataOutputStream out = new DataOutputStream(sock.getOutputStream());
out.writeShort(DataTransferProtocol.DATA_TRANSFER_VERSION);
out.writeByte(DataTransferProtocol.OP_REPLACE_BLOCK);
out.writeInt(namespaceId);
out.writeLong(block.getBlockId());
out.writeLong(block.getGenerationStamp());
Text.writeString(out, source.getStorageID());
sourceProxy.write(out);
out.flush();
// receiveResponse
DataInputStream reply = new DataInputStream(sock.getInputStream());
short status = reply.readShort();
if(status == DataTransferProtocol.OP_STATUS_SUCCESS) {
return true;
}
return false;
}
@Override
public void run() {
try {
Socket socket = new Socket(hostIP, port);
transceiver = new SocketTransceiver(socket) {
@Override
public void onReceive(InetAddress addr, String s) {
TcpClient.this.onReceive(this, s);
}
@Override
public void onDisconnect(InetAddress addr) {
connect = false;
TcpClient.this.onDisconnect(this);
}
};
transceiver.start();
connect = true;
this.onConnect(transceiver);
} catch (Exception e) {
e.printStackTrace();
this.onConnectFailed();
}
}
/**
* Create a socket for a write pipeline
* @param first the first datanode
* @param length the pipeline length
* @param client client
* @return the socket connected to the first datanode
*/
static Socket createSocketForPipeline(final DatanodeInfo first,
final int length, final DFSClient client) throws IOException {
final String dnAddr = first.getXferAddr(
client.getConf().connectToDnViaHostname);
if (DFSClient.LOG.isDebugEnabled()) {
DFSClient.LOG.debug("Connecting to datanode " + dnAddr);
}
final InetSocketAddress isa = NetUtils.createSocketAddr(dnAddr);
final Socket sock = client.socketFactory.createSocket();
final int timeout = client.getDatanodeReadTimeout(length);
NetUtils.connect(sock, isa, client.getRandomLocalInterfaceAddr(), client.getConf().socketTimeout);
sock.setSoTimeout(timeout);
sock.setSendBufferSize(HdfsConstants.DEFAULT_DATA_SOCKET_SIZE);
if(DFSClient.LOG.isDebugEnabled()) {
DFSClient.LOG.debug("Send buf size " + sock.getSendBufferSize());
}
return sock;
}
@Override
protected synchronized boolean closeOutputStream() {
final boolean closed = super.closeOutputStream();
if (reconnector != null) {
reconnector.shutdown();
reconnector.interrupt();
reconnector = null;
}
final Socket oldSocket = socket;
socket = null;
if (oldSocket != null) {
try {
oldSocket.close();
} catch (final IOException e) {
LOGGER.error("Could not close socket {}", socket);
return false;
}
}
return closed;
}
static SocketFactory mockSocketFactory(OutputStream out, InputStream in) {
try {
Socket socket = mock(Socket.class);
when(socket.getOutputStream()).thenReturn(out);
when(socket.getInputStream()).thenReturn(in);
SocketFactory factory = mock(SocketFactory.class);
when(factory.createSocket()).thenReturn(socket);
when(factory.createSocket(anyString(), anyInt())).thenReturn(socket);
return factory;
} catch (Exception e) {
e.printStackTrace();
throw new AssertionError("Cannot be here!");
}
}
/**
Creates a client that will connect to the specified address.
It will map messages as defined by the specified object model.
@param addr an server address on the form 'host:port'
@param om an object model
@throws BlinkException if there is a schema or binding problem
@throws IOException if there is a socket problem
*/
public Client (String addr, ObjectModel om)
throws BlinkException, IOException
{
String [] parts = addr.split (":");
if (parts.length != 2)
throw new IllegalArgumentException (
"Address must be on the form 'host:port'");
this.sock = new Socket (parts [0], Integer.parseInt (parts [1]));
this.om = om;
this.oreg = new DefaultObsRegistry (om);
this.os = sock.getOutputStream ();
this.wr = new CompactWriter (om, os);
this.udpsock = null;
this.bs = null;
}
public static void test(Socket s1, Socket s2, String mesg) throws Exception {
OutputStream os = s1.getOutputStream();
os.write("This is a message".getBytes("US-ASCII"));
InputStream in = s2.getInputStream();
s2.shutdownInput();
if (in.available() != 0) {
failed = true;
System.out.println(mesg + ":" + s2 + " in.available() should be 0, " +
"but returns "+ in.available());
}
byte[] ba = new byte[2];
if (in.read() != -1 ||
in.read(ba) != -1 ||
in.read(ba, 0, ba.length) != -1) {
failed = true;
System.out.append(mesg + ":" + s2 + " in.read() should be -1");
}
}
/**
* Construct a suitable stream for the passed-in socket. No assumptions
* are made about the passed-in socket except that a) it's not null, and
* b) it's been initialized and set up for reading (or at least the successful
* retrieval of a suitable input stream) by the caller.
*
* @param socket non-null socket
*/
public RpcSocketInputStream(Socket socket, ServerStats stats) {
super();
if (socket == null) {
throw new NullPointerError(
"null RPC socket passed to RpcSocketInputStream constructor");
}
this.socket = socket;
this.stats = stats;
try {
this.socketStream = socket.getInputStream();
} catch (IOException ioexc) {
Log.error("Unexpected I/O exception thrown during input stream retrieval"
+ " in RpcSocketInputStream constructor: " + ioexc.getLocalizedMessage());
Log.exception(ioexc);
throw new P4JavaError(
"Unexpected I/O exception thrown during input stream retrieval"
+ " in RpcSocketInputStream constructor: " + ioexc.getLocalizedMessage());
}
}
/**
* Creates a new instance.
*/
public DefaultSocketChannelConfig(SocketChannel channel, Socket javaSocket) {
super(channel);
if (javaSocket == null) {
throw new NullPointerException("javaSocket");
}
this.javaSocket = javaSocket;
// Enable TCP_NODELAY by default if possible.
if (PlatformDependent.canEnableTcpNoDelayByDefault()) {
try {
setTcpNoDelay(true);
} catch (Exception e) {
// Ignore.
}
}
}
public String chooseClientAlias(String[] keyTypes, Principal[] issuers,
Socket socket) {
String retval;
if (keyTypes == null) {
return null;
}
/*
* Scan the list, look for something we can pass back.
*/
for (int i = 0; i < keyTypes.length; i++) {
if ((retval = theX509KeyManager.chooseClientAlias(keyTypes[i],
issuers)) != null)
return retval;
}
return null;
}
private void send200(Socket clientSocket) throws IOException {
OutputStream out = clientSocket.getOutputStream();
PrintWriter pout = new PrintWriter(out);
pout.println("HTTP/1.1 200 OK");
pout.println();
pout.flush();
}
public synchronized void sendMessage(ApnsNotification m) throws NetworkIOException {
int attempts = 0;
while (true) {
try {
attempts++;
Socket socket = socket();
socket.getOutputStream().write(m.marshall());
socket.getOutputStream().flush();
delegate.messageSent(m);
logger.debug("Message \"{}\" sent", m);
attempts = 0;
break;
} catch (Exception e) {
if (attempts >= RETRIES) {
logger.error("Couldn't send message " + m, e);
delegate.messageSendFailed(m, e);
Utilities.wrapAndThrowAsRuntimeException(e);
}
logger.warn("Failed to send message " + m + "... trying again", e);
// The first failure might be due to closed connection
// don't delay quite yet
if (attempts != 1)
Utilities.sleep(DELAY_IN_MS);
Utilities.close(socket);
socket = null;
}
}
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType,
Socket socket) throws CertificateException {
if (delegate != null) {
delegate.checkClientTrusted(chain, authType);
}
}
void simpleDataExchange(Socket s1, Socket s2) throws Exception {
try (final InputStream i1 = s1.getInputStream();
final InputStream i2 = s2.getInputStream();
final OutputStream o1 = s1.getOutputStream();
final OutputStream o2 = s2.getOutputStream()) {
startSimpleWriter("simpleWriter1", o1, 100);
startSimpleWriter("simpleWriter2", o2, 200);
simpleRead(i2, 100);
simpleRead(i1, 200);
}
}
@Override
public void run() {
while (running) {
try (Socket socket = new Socket(HOST.toString(), PORT.toInt())) {
try (
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"))
) {
activeConnection = true;
log.info("Connection to propresenter established at " + HOST.toString() + ":" + PORT.toString());
out.println(getLoginString());
String loginResponse = in.readLine();
if (SUCCESSFUL_LOGIN.equals(loginResponse) || SUCCESSFUL_LOGIN_WINDOWS.equals(loginResponse)) {
log.info("Login succeeded");
} else {
log.error("Login failed with incorrect password: " + PASSWORD.toString() + ", with response: " + loginResponse);
running = false;
}
while (running && activeConnection && socket.isConnected()) {
activeConnection = update(in);
sleep(RESPONSE_TIME_MILLIS.toInt());
}
log.info("Connection lost");
}
} catch (IOException e) {
log.error("Connection to propresenter failed at " + HOST.toString() + ":" + PORT.toString(), e);
}
sleep(500);
}
log.info("Closing program");
Platform.exit();
}
private void closeSocketOutput(Socket socket) {
try {
if (!socket.isOutputShutdown()) {
socket.shutdownOutput();
}
} catch (IOException e) {
VenvyLog.w("Failed to close socket on proxy side: {}. It seems client have already closed connection.", e.getMessage());
}
}
public static BioSocketChannel open(SocketAddress address) throws Exception {
Socket socket = new Socket();
socket.setSoTimeout(BioSocketChannel.SO_TIMEOUT);
socket.setTcpNoDelay(true);
socket.setKeepAlive(true);
socket.setReuseAddress(true);
socket.connect(address, BioSocketChannel.DEFAULT_CONNECT_TIMEOUT);
return new BioSocketChannel(socket);
}
public static void main(String args[]) throws Exception {
// bind to a random port
if (args.length < 1) {
System.err.println("First argument should be path to output file.");
}
String outFileName = args[0];
ServerSocket ss = new ServerSocket(0);
int port = ss.getLocalPort();
int pid = ProcessTools.getProcessId();
System.out.println("shutdownPort=" + port);
System.out.println("pid=" + pid);
System.out.flush();
try (PrintWriter writer = new PrintWriter(outFileName)) {
writer.println("shutdownPort=" + port);
writer.println("pid=" + pid);
writer.println("done");
writer.flush();
}
// wait for test harness to connect
Socket s = ss.accept();
s.close();
ss.close();
}
/**
* Starts a HTTP server to given port.<p>
* Throws an IOException if the socket is already in use
*/
//private HTTPSession session;
public CloudStreamServer(int port, File wwwroot ) throws IOException
{
myTcpPort = port;
this.myRootDir = wwwroot;
myServerSocket = new ServerSocket( myTcpPort );
myThread = new Thread( new Runnable()
{
public void run()
{
try
{
while( true ){
// if(session!=null){
// session.interrupt();
// try {
// session.join();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
Socket accept = myServerSocket.accept();
new HTTPSession(accept);
}
}
catch ( IOException ioe )
{}
}
});
myThread.setDaemon( true );
myThread.start();
}
@Override
public String chooseClientAlias(String[] keyType, Principal[] issuers,
Socket socket) {
String nap = ((SSLSocket) socket).getHandshakeApplicationProtocol();
checkALPN(nap);
return akm.chooseClientAlias(keyType, issuers, socket);
}
public void prefill(final int numberOfSocketSets) throws Exception {
final Object[] socketSets = new Object[numberOfSocketSets];
logForInfo("pre-filling socket pool with " + numberOfSocketSets + " connections per server");
for (int index = 0; index < numberOfSocketSets; index++) {
socketSets[index] = getFromPool(true);
}
for (int index = 0; index < numberOfSocketSets; index++) {
returnToPool((Socket[]) socketSets[index]);
}
}
public ServerProcess(String u, String p, String db, Socket socket, int seq) {
sequence = seq;
this.socket = socket;
this.u = u;
this.p = p;
this.db = db;
}
static List<SNIServerName> getRequestedServerNames(Socket socket) {
if (socket != null && socket.isConnected() &&
socket instanceof SSLSocket) {
return getRequestedServerNames(
((SSLSocket)socket).getHandshakeSession());
}
return Collections.<SNIServerName>emptyList();
}
@Test
public void testAcceptSocketRejectsAlways()
throws UnknownHostException, IOException, InterruptedException {
reset();
TestSubscriber<Object> ts = TestSubscriber.create();
try {
int bufferSize = 4;
AtomicInteger port = new AtomicInteger();
IO.serverSocketAutoAllocatePort(Actions.setAtomic(port)) //
.readTimeoutMs(10000) //
.acceptTimeoutMs(200) //
.bufferSize(bufferSize) //
.acceptSocketIf(Functions.alwaysFalse()) //
.create() //
.subscribeOn(scheduler) //
.subscribe(ts);
Thread.sleep(300);
Socket socket = new Socket("localhost", port.get());
OutputStream out = socket.getOutputStream();
out.write("12345678901234567890".getBytes());
out.close();
socket.close();
Thread.sleep(1000);
ts.assertNoValues();
} finally {
// will close server socket
ts.unsubscribe();
}
}
/**
* send quit command to server and close socket
*
* @param sock the Socket object
*/
public static void closeSocket(Socket sock) throws IOException {
byte[] header;
header = packHeader(FDFS_PROTO_CMD_QUIT, 0, (byte) 0);
sock.getOutputStream().write(header);
sock.close();
}
@Override
public Socket createSocket(InetAddress ia, int i, InetAddress localAddress, int localPort) throws IOException {
Socket socket = new Socket(proxy);
socket.bind(new InetSocketAddress(localAddress, localPort));
socket.connect(new InetSocketAddress(ia, i));
return socket;
}
@Override
public Socket createSocket(String host, int port) throws IOException,
UnknownHostException {
Socket socket = createSocket();
socket.connect(new InetSocketAddress(host, port));
return socket;
}
/**
* Simple socket content reader from given container:port
*
* @param container to query
* @param port to send request to
* @return socket reader content
* @throws IOException if any
*/
private String readResponse(GenericContainer container, Integer port) throws IOException {
try (
final BufferedReader reader = Unreliables.retryUntilSuccess(10, TimeUnit.SECONDS,
() -> {
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
final Socket socket = new Socket(container.getHost(), port);
return new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
)
) {
return reader.readLine();
}
}