import java.net.*;
import java.io.*;class TcpClient {
public static void main(String[] args) throws Exception{
//1.建立Socket服务
Socket sk = new Socket("192.168.0.105",10003);
//2.运用Socket服务的getOutputStream()方法写数据
OutputStream out = sk.getOutputStream();
out.write("wo yao xue bian cheng".getBytes());
//3.关闭资源
sk.close();
}
}
class TcpServer{
public static void main(String[] args) throws Exception{
//1.建立Socket 服务并监听端口
ServerSocket ss = new ServerSocket(10003);
//2.通过accept()方法获取客户端对象
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.print("ip="+ip);
//3.使用客户端对象获取数据
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
System.out.print(new String(buf,0,len));
//4.关闭资源
s.close();
ss.close();
}
}
客户端与服务端数据交互
import java.io.*;
import java.net.*;
class TcpClient{
public static void main(String[] args) throws Exception{
Socket sk = new Socket("10.56.192.176",10005);
OutputStream out = sk.getOutputStream();
out.write("wo yoa xue biancheng".getBytes());
InputStream in = sk.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
System.out.print(new String(buf,0,len));
sk.close();
}
}
class TcpServer {
public static void main(String[] args)throws Exception{
ServerSocket ss = new ServerSocket(10005);
Socket s = ss.accept();
String ip = s.getInetAddress().getHostAddress();
System.out.print("ip=" + ip);
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
System.out.print(new String(buf,0,len));
OutputStream out = s.getOutputStream();
out.write("哥们收到".getBytes());
s.close();
ss.close();
}
}