使用TCP协议编写一个网络程序,设置服务器端的监听端口是8002,当与客户端建立连接后,服务器端向客户端发送数据“Hello, world”,客户端收到数据后打印输出。
mytcpserver.java
package javasocket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class mytcpserver {
public static void main(String[] args) {
try{
ServerSocket s = new ServerSocket(8002);
while(true){
Socket s1 = s.accept();
OutputStream os = s1.getOutputStream();
DataOutputStream dis = new DataOutputStream(os);
dis.writeUTF("Hello,wrold!");
dis.close();
s1.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}
mytcpclient.java
package javasocket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class mytcpclient {
public static void main(String[] args) {
try{
Socket s1 = new Socket("127.0.0.1", 8002);
InputStream is = s1.getInputStream();
DataInputStream dos= new DataInputStream(is);
System.out.println(dos.readUTF());
dos.close();
s1.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
运行结果:
mytcpclint:
Hello,wrold!