需求:给服务端发一个文本数据。 步骤:客户端:1、创建Socket服务,并指定要连接的主机和端口,创建成功,就连接,有Socket流,既有输入流,也有输出流,通过getOutputStream()方法和getInputStream()方法获取;2、向输出流中输出文本数据;3、关闭资源。服务端:1、建立服务端的socket服务ServerSocket()并监听一个端口,,2、获取连接过来的客户端对象,通过servetSocket的accept()方法完成,没有连接就会等,所以这个方法是阻塞式的,客户端如果发过来数据,那么服务端要使用对应的客户端对象并获取到该客户端对象的读取流来读取发过来的数据并打印在控制台,4、关闭服务端(可选)。
代码如下:
import java.net.*;
import java.io.*;
class TCPclient{
public static void main(String[] args){
Socket s=null;
try{
s=new Socket(InetAddress.getLocalHost(),18888);
}catch(UnknownHostException e1){
throw new RuntimeException(e1);
}catch(IOException e2){
throw new RuntimeException(e2);
}
BufferedWriter bw=null;
try{
bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
}catch(IOException e3){
throw new RuntimeException(e3);
}
try{
bw.write("TCP客户端来了!");
bw.newLine();
bw.flush();
}catch(IOException e4){
throw new RuntimeException(e4);
}
try{
s.close();
}catch(IOException e5){
throw new RuntimeException(e5);
}
}
}
import java.net.*;
import java.io.*;
class TCPserver{
public static void main(String[] args){
ServerSocket ss=null;
Socket s=null;
try{
ss=new ServerSocket(18888);
}catch(SocketException e1){
throw new RuntimeException(e1);
}catch(IOException e2){
throw new RuntimeException(e2);
}
try{
s=ss.accept();
}catch(IOException e3){
throw new RuntimeException(e3);
}
System.out.println("ip"+s.getLocalAddress().getHostAddress()+"......"+"已连接");
BufferedReader br=null;
try{
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
}catch(IOException e4){
throw new RuntimeException(e4);
}
String buff=null;
try{
while((buff=br.readLine())!=null)
System.out.println("ip"+s.getLocalAddress().getHostAddress()+"......"+buff);
}catch(IOException e5){
throw new RuntimeException(e5);
}
try{
s.close();
}catch(IOException e6){
throw new RuntimeException(e6);
}
try{
ss.close();
}catch(IOException e7){
throw new RuntimeException(e7);
}
}
}
|
|