标签: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 socket serversocket 客户端 服务器端
原文地址:http://blog.51cto.com/11359581/2047893