使用TCP协议编写一个网络程序,设置服务器端的监听端口是8002,当与客户端建立连接后,服务器端向客户端发送数据“Hello, world”,客户端收到数据后打印输出。
服务器端代码:
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Tcpfwq {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
new TCPServer().listen();
}
}
class TCPServer{
private static final int PORT=8002;
public void listen() throws Exception{
ServerSocket seso=new ServerSocket(PORT);
Socket clie=seso.accept();
OutputStream os=clie.getOutputStream();
os.write(("Hello, world").getBytes());
Thread.sleep(5000);
os.close();
clie.close();
}
}
客户端代码:
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
public class Tcpkht {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
new TCPClient().connect();
}
}
class TCPClient{
public void connect() throws Exception{
// TODO Auto-generated method stub
Socket client=new Socket(InetAddress.getLocalHost(),8002);
InputStream is=client.getInputStream();
byte[] buf=new byte[1024];
int len=is.read(buf);
System.out.println(new String(buf,0,len));
client.close();
}
}
运行结果图: