1. 程式人生 > >TCP發送接收數據2

TCP發送接收數據2

tcp socket serversocket 客戶端 服務器端

//客戶端

package liu.net.tcp;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.Socket;

import java.net.UnknownHostException;


public class Client3 {

public static void main(String[] args) throws UnknownHostException, IOException {

System.out.println("客戶端啟動。。。。");

//發數據給服務端

Socket s = new Socket("127.0.0.1",8899);

OutputStream out = s.getOutputStream();

out.write("client send data to server".getBytes());

//接收服務端的數據

InputStream in = s.getInputStream();

byte[] buf = new byte[1024];

int len = in.read(buf);

String data = new String(buf,0,len);

System.out.println("從服務端收到的數據:"+data);

s.close();

}

}




//服務器端

package liu.net.tcp;


import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.ServerSocket;

import java.net.Socket;


public class Server3 {

public static void main(String[] args) throws IOException {

/* 客戶端發送數據給服務端

* 服務端收到數據後發信息給客戶端

*/

System.out.println("服務端啟動。。。。");

//接收客戶端發來的數據

ServerSocket ss = new ServerSocket(8899);

Socket s = ss.accept();

byte[] buf = new byte[1024];

InputStream in = s.getInputStream();

int len = in.read(buf);

String data = new String(buf,0,len);

System.out.println("服務端收到的數據:"+data);

//發數據給客戶端

String dataToClient = "11111";

OutputStream out = s.getOutputStream();

out.write(dataToClient.getBytes());

s.close();


ss.close();

}

}



TCP發送接收數據2