JAVA TCP

来源:互联网 发布:苏联狗头实验 知乎 编辑:程序博客网 时间:2024/06/08 11:06
 
TcpClient.javapackage javanet;import java.io.*;import java.net.*;public class TcpClient {public static void main(String args[]) throws Exception {Socket s = new Socket("172.16.215.105",2222);OutputStream out = s.getOutputStream();/* * 向服务端发送信息 * */out.write("I'm comming".getBytes());/* * 等待服务装返回信息 * */byte buf[] = new byte[1024];InputStream in = s.getInputStream();int length = in.read(buf);System.out.println(new String(buf,0,length));s.close();}}TcpServer.java

package javanet;import java.io.*;import java.net.*;public class TcpServer {

 public static void main(String args[]) throws Exception  {  ServerSocket server = new ServerSocket(2222);  Socket s = server.accept();    /*   *  接收客户端发送的数据   * */  InputStream in = s.getInputStream();  byte buf[] = new byte[1024];  int length = in.read(buf);  System.out.println(new String(buf,0,length));  /*   *   收到数据后向客户端返回一个收到信息   * */  OutputStream out = s.getOutputStream();  out.write("Good...".getBytes());  s.close();     }}


原创粉丝点击