菜鸟求助 serversock连不上 纠结了一个晚上了
这是client端的
import java.awt.*;
import java.awt.event.*;
import java.io.DataOutputStream;
import
java.io.IOException;
import java.net.Socket;
import java.net.
UnknownHostException;
public class ChatClient extends Frame{
TextField t1 =new TextField();
TextArea t2 = new TextArea();
Socket s ;
DataOutputStream dos = null;
public static void main(String[] args) throws Exception,
IOException {
new ChatClient().LunchFrame();
}
public void LunchFrame()
{
this.setBounds(300, 300, 200, 600);
this.setVisible(true);
this.add(t1,"South");
this.add(t2 , "North");
t1.addActionListener(new T1Listenrt());
this.pack();
this.conect();
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
shut();
System.exit(0);
}
});
}
public void conect()
{
try {
s = new Socket("127.0.0.1" , 8888);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
dos = new DataOutputStream(s.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void shut(){
try {
dos.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private class T1Listenrt implements ActionListener
{
public void actionPerformed(ActionEvent e) {
String str = t1.getText();
t2.setText(str);
t1.setText("");
try {
dos.writeUTF(str);
dos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
下面的事server端的
import java.io.DataInputStream;
import java.io.IOException;
import java.net.*;
public class ChatServer {
public static void main(String[] args) throws IOException {
boolean con1 = false;
ServerSocket ss = new ServerSocket(8888);
con1 = true;
while (true)
{
boolean con2 = false;
Socket s = ss.accept();
con2 = true;
while(con2)
{
DataInputStream dos = new DataInputStream(s.getInputStream());
String str = dos.readUTF();
System.out.println(str);
}
}
}
}
------解决方案--------------------
我把你的代码 测试了一个 可以连上。
除了server端 少一个大括号