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();
}
}