首页 > 代码库 > java网络编程TCP
java网络编程TCP
图片来自网络
【服务端】
import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.ServerSocket;import java.net.Socket;//服务端public class MyServer { public static void main(String[] args) { ServerSocket serverSocket = null; Socket socket = null; try { //创建监听1515端口的ServerSocket对象 serverSocket = new ServerSocket(1515); //堵塞等待客户端的请求,当收到请求就返回Socket对象 socket = serverSocket.accept(); //从Socket对象获取输入流和输出流 InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); //通过输入流读取客户端发送的数据 byte[] bt = new byte[1024]; int len = in.read(bt); String data = new String(bt, 0, len); System.out.println(data); //通过输出流向客户端返回数据 out.write("服务器已收到!!!".getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { //关闭资源 if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }}
【客户端】
import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.Socket;import java.net.UnknownHostException;//客户端public class MyClient { public static void main(String[] args) { Socket socket = null; try { //创建连接服务端的Socket对象 socket = new Socket("127.0.0.1", 1515); //从Socket对象获取输入流和输出流 InputStream in = socket.getInputStream(); OutputStream out = socket.getOutputStream(); //通过输出流向服务端发送数据 out.write("来自客户端!!!".getBytes()); //通过输入流读取服务端返回的数据 byte[] bt = new byte[1024]; int len = in.read(bt); String data = new String(bt, 0, len); System.out.println(data); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { //关闭资源 if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }}
java网络编程TCP
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。