import java.io.IOException; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class TCPServer { // 建立ServerSocket,并设置其端口号 private ServerSocket ss; public static final int port = 8962; public TCPServer() { try { ss = new ServerSocket(port); } catch (IOException e) { e.printStackTrace(); } } public void setConnection() throws IOException { // 建立服务器端的Socket Socket s; OutputStream os; try { // ServerSocke.accept()t返回一个Socket对象 s = ss.accept(); os = s.getOutputStream(); os.write("hello".getBytes()); os.close(); s.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) throws IOException { TCPServer ms = new TCPServer(); ms.setConnection(); } }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.Socket; public class TCPClient { public static final String IP = "192.168.0.157"; public static final int port = 8962; private Socket s; public TCPClient() throws IOException { try { s = new Socket(IP, port); } catch (IOException e) { e.printStackTrace(); } } public void setConnection() throws IOException { InputStream is; try { is = s.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); System.out.println(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } public static void main(String args[]) throws IOException { TCPClient mc = new TCPClient(); mc.setConnection(); } }
posted on 2012-03-16 20:49 Snowberg 阅读(1466) 评论(0) 收藏 举报
博客园 © 2004-2025 浙公网安备 33010602011771号 浙ICP备2021040463号-3