[英]Tcpclient - NetworkStream - TcpListener in Java
我有幾個月前用C#編寫的PacketLogger的代碼:
internal class conexion
{
public static TcpClient client;
public static NetworkStream clientstream;
public static string ip = "92.222.120.7";
public static TcpListener listener;
public static int port = 5921;
public static TcpClient server;
public static NetworkStream serverstream;
public static void connect()
{
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
client = listener.AcceptTcpClient();
server = new TcpClient(ip, port);
Console.WriteLine("Conectado!");
while (client.Available < 1)
{
}
byte[] data = new byte[client.Available];
client.GetStream().Read(data, 0, client.Available);
server.GetStream().Write(data, 0, data.Length);
server.GetStream().Flush();
while (server.Available < 1)
{
}
data = new byte[server.Available];
server.GetStream().Read(data, 0, server.Available);
client.GetStream().Write(data, 0, data.Length);
client.GetStream().Flush();
server.Close();
server = new TcpClient(ip, port);
client.Close();
}
我開始用Java編程,並且需要幫助來傳遞此Java代碼。
請幫我!!!
我不知道是否使用Sockets或其他方法對不起我的英語,我是西班牙語
Casi entiendo queeres hacer con tu codigo,pero no。 消費者在任何情況下都必須保持自己的穩定,而初級或中級以下的客戶則應與自己的客戶合作,類似的產品也應運而生。
package com.quick.random;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class JavaSocketExample {
private static String host = "localhost";
private static int port = 5921;
public static void main(String[] args) throws IOException {
// el servidor corre en un hilo aparte, correrlo en el mismo hilo seria
// raro (y claro, no funcionaria)
new Thread(new Runnable() {
@Override
public void run() {
try {
runServer();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
// el cliente puede correr en el hilo principal
runClient();
}
protected static void runServer() throws IOException {
ServerSocket listener = new ServerSocket(port);
listener.setSoTimeout(15000);
System.out.println("el servidor espera una conexion entrante");
Socket client = listener.accept(); // client no es el mejor nombre
System.out.println("el servidor ha establecido una conexión con "
+ client.getInetAddress());
byte[] data = new byte[client.getInputStream().available()];
client.getInputStream().read(data);
System.out.println("SERVER recibe de CLIENT : " + new String(data));
client.close();
listener.close();
System.out.println("el servidor ha terminado");
}
private static void runClient() throws UnknownHostException, IOException {
Socket server = new Socket(host, port);
server.getOutputStream().write("hola mundo".getBytes());
server.close();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.