lesson 11:使用TCP协议编写一个网络程序,设置服务器端的监听端口是8002,当与客户端建立连接后,服务器端向客户端发送数据“Hello, world”,客户端收到数据后打印输出。

题目:

 

使用TCP协议编写一个网络程序,设置服务器端的监听端口是8002,当与客户端建立连接后,服务器端向客户端发送数据“Hello,world”,客户端收到数据后打印输出。

 

代码:

 

 

package TCP;  
  
import java.io.InputStream;  
import java.net.InetAddress;  
import java.net.Socket;  
  
public class TCPClientTest {  
  
    public static void main(String[] args) throws Exception {  
        // TODO Auto-generated method stub  
        new TCPClient().connect();  
    }  
  
}  
  
class TCPClient{  
    private static final int PORT = 8002;  
    public void connect() throws Exception{  
        Socket client = new Socket(InetAddress.getLocalHost(),PORT);  
        InputStream is = client.getInputStream();  
        byte[] buf = new byte[1024];  
        int len = is.read(buf);  
        System.out.println(new String(buf,0,len));  
        client.close();  
    }  
}  
[java] view plain copy
package TCP;  
  
import java.io.OutputStream;  
import java.net.ServerSocket;  
import java.net.Socket;  
  
public class TCPServerTest {  
  
    public static void main(String[] args) throws Exception  {  
        new TCPServer().listen();  
    }  
      
}  
class TCPServer  
{  
    private static final int PORT = 8002;  
    public void listen() throws Exception{  
        ServerSocket serverSocket = new ServerSocket(PORT);  
        Socket client = serverSocket.accept();  
        OutputStream os = client.getOutputStream();  
        System.out.println("开始与客户端交互数据");  
        os.write(("Hello World!").getBytes());  
        Thread.sleep(5000);  
        System.out.println("结束与客户端交互数据");  
        os.close();  
        client.close();  
    }  
  
}  

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章