- import java.io.*;
- import java.net.*;
- public class TCPServerDemo {
- public static void main(String []args) throws IOException, InterruptedException{
- ServerSocket ss = new ServerSocket(1999);
- Socket socket = ss.accept();//通过accept方法获取连接过来的客户端对象。
- InputStream ips = socket.getInputStream();//获取客户端发送过来的数据,使用客户端对象的读取流来读取数据。
- byte[] buf = new byte[1024];
- int len = ips.read(buf);
- System.out.println(new String(buf,0,len));
- OutputStream ops = socket.getOutputStream();
- System.out.println((socket.getInetAddress().getHostName()+"::"+socket.getPort()+"::"+new String(buf,0,len)));
- Thread.sleep(10000);
- ops.write("收到".getBytes());
- System.out.println("发送成功");
-
- socket.close();
- ss.close();
- }
- }
- [code]import java.net.*;
- import java.io.*;
- public class TCPClientDemo {
- public static void main(String []args) throws IOException{
- Socket s = new Socket("192.168.1.2",1999);
- OutputStream out = s.getOutputStream(); //获得输出流
- out.write("这个是TCP Client Demo".getBytes());
-
- InputStream ips = s.getInputStream();
- System.out.println("成功1");
- byte[] bufIn = new byte[1024];
- int num = ips.read(bufIn);
- System.out.println(new String(bufIn,0,num));
- System.out.println("成功2");
- out.close();
- s.close();
- }
- }
复制代码 [/code]
这个是可以的代码 |