java如何通过tcp向指定的IP发送指令并获得返回的包?
1个回答
展开全部
以下是一个展示java使用tcp通讯的简单例子,包括服务器和客户端代码:
/**
*TCPServer
*/
import java.io.*;
import java.net.*;
class TCPServer{
public static void main(String[] args)throws IOException{
ServerSocket listen = new ServerSocket(5050);
Socket server = listen.accept();
InputStream in = server.getInputStream();
OutputStream out = server.getOutputStream();
char c = (char)in.read();
System.out.println("收到:" + c);
out.write('s');
out.close();
in.close();
server.close();
listen.close();
}
}
/**
*TCPClient
*/
import java.io.*;
import java.net.*;
class TCPClient{
public static void main(String[] args)throws IOException{
Socket client = new Socket("127.0.0.1" , 5050);
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
out.write('c');
char c = (char)in.read();
System.out.println("收到:" + c);
out.close();
in.close();
client.close();
}
}
/**
*TCPServer
*/
import java.io.*;
import java.net.*;
class TCPServer{
public static void main(String[] args)throws IOException{
ServerSocket listen = new ServerSocket(5050);
Socket server = listen.accept();
InputStream in = server.getInputStream();
OutputStream out = server.getOutputStream();
char c = (char)in.read();
System.out.println("收到:" + c);
out.write('s');
out.close();
in.close();
server.close();
listen.close();
}
}
/**
*TCPClient
*/
import java.io.*;
import java.net.*;
class TCPClient{
public static void main(String[] args)throws IOException{
Socket client = new Socket("127.0.0.1" , 5050);
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
out.write('c');
char c = (char)in.read();
System.out.println("收到:" + c);
out.close();
in.close();
client.close();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询