客户端程序代码:publicclassClientSocketFrameextendsJFrame{JTextAreatextArea;Socketsocket;publicClientSocketFrame(){setTitle("建立客户端套接字");setDefaultCloseOperation(J...
客户端程序代码:
public class ClientSocketFrame extends JFrame {
JTextArea textArea ;
Socket socket;
public ClientSocketFrame(){
setTitle("建立客户端套接字");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(480, 330);
getContentPane().setLayout(new BorderLayout(0, 0));
JScrollPane scrollPane = new JScrollPane();
getContentPane().add(scrollPane, BorderLayout.CENTER);
textArea = new JTextArea();
textArea.setPreferredSize(new Dimension(450, 280));
scrollPane.setViewportView(textArea);
}
public void connect(){
textArea.append("尝试连接......\n");
try{
socket = new Socket("127.0.0.1", 8888);//创建一个流套接字并将其连接到指定主机上的指定端口号
textArea.append("完成连接。\n");
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run(){
ClientSocketFrame frame = new ClientSocketFrame();
frame.setVisible(true);
frame.connect();
}
});
}
在网上试了很多IP和端口,还是连接不上,用本机IP也连接不 上或拒绝连接或是黑屏,new ServerSocket(0);设置空闲端口连接也不行,本机是JDK1.7,WIN7,谢谢大侠。
服务器端程序代码:
展开