Java网络编程(TCP协议-服务端和客户端交互)

客户端:

 package WebProgramingDemo;

 import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException; public class SocketDemo { /**
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws IOException { Socket s=new Socket("192.168.2.103",10002);
OutputStream out=s.getOutputStream();
out.write("Java".getBytes());
InputStream is=s.getInputStream();
byte buf[]=new byte[1024];
int len=is.read(buf);
System.out.println(new String(buf,0,len));
s.close();
} }

服务端:

 package WebProgramingDemo;

 import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket; public class ServerSocketDemo { /**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException { ServerSocket ss = new ServerSocket(10002);
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.println(ip + "....connected....");
InputStream in = s.getInputStream();
int len = 0;
byte[] buf = new byte[1024];
len = in.read(buf);
System.out.println(new String(buf, 0, len));
OutputStream os=s.getOutputStream();
os.write("收到".getBytes());
os.close();
s.close();
ss.close();
} }
上一篇:GPU驱动兼容性问题


下一篇:Java网络编程——TCP实例