服务器端
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.lang.*;
public class ServerSocketTest
{
public static void main(String [] args)
{
JFrame2 jf = new JFrame2("服务器端");
}
}
class JFrame2 extends JFrame implements ActionListener
{
JPanel jp = new JPanel();
JButton jb = new JButton("监听端口");
JLabel jl = new JLabel("设置端口");
JTextField jtf = new JTextField(10);
JTextArea jta = new JTextArea(5,6);
Socket socket;
int i =1;
JFrame2(String s)
{
super(s);
setSize(300,350);
setVisible(true);
add(jp,"North");
jp.add(jl);
jp.add(jtf);
jp.add(jb);
add(jta,"Center");
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
jb.addActionListener(this);
}
public void run()
{
String s = null;
try
{
while (true)
{
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dio = new DataOutputStream(socket.getOutputStream());
dio.writeUTF("嘎嘎,我是服务器");
s = dis.readUTF();
if (s.equals("end"))
{
dio.close();
dis.close();
socket.close();
break;
}
jta.append("第"+i+"个客户端发送信息: "+s); }
}
catch (IOException e)
{
System.out.println(e);
}
}
public void actionPerformed(ActionEvent a)
{
try
{
int ip = Integer.parseInt(jtf.getText());
ServerSocket ss = new ServerSocket(ip);
while (true)
{
Socket socket = ss.accept();
Thread th = new Thread();
th.start();
i++;
}
}
catch (IOException e)
{
System.out.println("服务器出错");
}
}
}
客户端
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
public class SocketTest
{
public static void main(String [] args)
{
JFrame1 jf = new JFrame1("客户端");
}
}
class JFrame1 extends JFrame
{
JPanel jp = new JPanel();
JButton jb = new JButton("连接");
JLabel jl = new JLabel("连接服务器端口");
JTextArea jta = new JTextArea(5,6);
JTextField jtf = new JTextField(10);
int ip;
JFrame1(String s)
{
super(s);
setSize(300,350);
setVisible(true);
add(jp,"North");
jp.add(jl);
jp.add(jtf);
jp.add(jb);
add(jta,"Center");
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
jb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent k)
{
String s = null;
int i =1;
try
{
ip = Integer.parseInt(jtf.getText());
Socket socket = new Socket("localhose",ip);
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dio = new DataOutputStream(socket.getOutputStream());
int p1 = socket.getPort();
int p2 = socket.getPort();
jta.append("获取到对方端口号:"+p1+"\n");
jta.append("本地端口号:  "+p2+"\n");
s = dis.readUTF();
jta.append("客户端收到: "+s);
if (i>10)
{
dio.writeUTF("end");
dio.close();
dis.close();
socket.close();
}
else
{
dio.writeUTF("哈哈,我来了");
i++;
}
}
catch (IOException e)
{
System.out.println("建立输入输出流错误");
}
}
});
}}一按监听端口服务器端就死掉了  

解决方案 »

  1.   


    public void actionPerformed(ActionEvent a)
        {
            try
            {
                int ip = Integer.parseInt(jtf.getText());
                ServerSocket ss = new ServerSocket(ip);    
                while (true)
                {
                    Socket socket = ss.accept();
                    Thread th = new Thread();
                    th.start();
                    i++;
                }
            }
            catch (IOException e)
            {
                System.out.println("服务器出错");
            }
        }
    Thread th = new Thread();这行是什么?你的线程实现类在那里?你启动一个空线程做什么?
      

  2.   

    另外一个问题,你的actionPerformed方法是个无限循环。好吧当前线程一直在这个方法里转如何去响应其他操作?
      

  3.   

    jb.addActionListener(this);
    你说的死掉,错误应该是源于这一句。你给这个按钮添加的监听事件不对。做web做多了,很久没玩过这个了。。把这个改成你服务端里面的写法。然后就像楼上说的,Thread th = new Thread();这种写法Thread th = new Thread(this);改成这样看看吧
      

  4.   

    楼主的意图是不是想使用新的线程去处理监听的到的客户端的socket 连接,如果是的话,你监听到的socket应该作为参数,传到线程里面去,然后在线程里面针对这个socket做处理。
      

  5.   

      
    我试过在线程里传入socket参数 可是还是不行
       问题都不知道出在那
      

  6.   

    写这种通信类的程序,不要把代码和swt/swing搅合到一块,要少做设计
    做一个专门负责通信的Handler类,专门用于监听/连接服务器,并启动启动接收、读取线程
    我这里有个例子,你参考一下:
    ClientHandler.java
    public class ClientHandler<T extends BaseTranMsg> {
    /** 套接字 */
    private Socket socket;
    /** 数据处理监听程序 */
    private IMsgListener<T> listener = null;
    /** 传送消息的类型 */
    private Class<T> baseClazz = null;
    /** 处理中标示 */
    private boolean isRunning = true;
    /** 待发送的消息 */
    private T msg = null;
    /** 套接字写入流 */
    private OutputStream os = null;
    /** 套接字读取流 */
    private InputStream is = null;
    /** 消息接收线程 */
    private Thread thrRecv = null;
    /** 消息发送线程 */
    private Thread thrSend = null; /**
     * 创建客户端处理实例
     * 
     * @param socket 连接到服务器的套接字
     * @param listener 数据处理监听程序
     * @param clazz 传送消息的类型
     */
    public ClientHandler(Socket socket, IMsgListener<T> listener, Class<T> clazz) {
    this.socket = socket;
    this.listener = listener;
    this.baseClazz = clazz; try {
    os = socket.getOutputStream();
    is = socket.getInputStream();
    } catch (Exception e) {
    //
    }
    } /**
     * 处理开始
     */
    public void startAction() {
    // 接受消息的线程
    thrRecv = new Thread(new Runnable() {
    @Override
    public void run() {
    try {
    while (isRunning) {
    if (listener == null) {
    break;
    }
    if (is.available() > 0) {
    listener.onMessage((T)BaseTranMsg.parseMsg(is, baseClazz));
    }
    Thread.sleep(500);
    }
    } catch (IOException e) {
    Log.e("ClientHandler-Reading", e.getMessage());
    isRunning = false;
    } catch (InterruptedException e) {
    Log.e("ClientHandler-Reading", e.getMessage());
    isRunning = false;
    } catch (NetException e) {
    // ignore
    isRunning = false;
    } finally {
    try {
    if (is != null) {
    is.close();
    }
    } catch (IOException e) {
    // ignore
    }
    }
    Log.d("ClientHandler-Reading", "stoped.");
    }
    });
    thrRecv.start(); // 发送消息线程
    thrSend = new Thread(new Runnable() {
    @Override
    public void run() {
    try {
    while (isRunning) {
    if (msg != null) {
    os.write(msg.toBytes());
    os.flush();
    msg = null;
    }
    // 发送完消息后,线程进入等待状态
    synchronized(ClientHandler.this) {
    ClientHandler.this.wait();
    }
    }
    } catch (Exception e) {
    Log.e("ClientHandler-Sending", e.getMessage());
    e.printStackTrace();
    isRunning = false;
    } finally {
    try {
    if (os != null) {
    os.close();
    }
    } catch (Exception ex) {
    // ignore
    }
    try {
    if (socket != null) {
    socket.close();
    }
    } catch (Exception ex) {
    // ignore
    }
    }
    Log.d("ClientHandler-Sending", "stoped.");
    }
    });
    thrSend.start();
    } /**
     * 发送消息
     * @param msg
     */
    public void sendMsg(T msg) {
    this.msg = msg;
    synchronized(this) {
    notify();
    }
    } /**
     * 处理结束
     */
    public void stopAction() {
    this.isRunning = false;
    try {
    thrRecv.join();
    } catch (InterruptedException e) {
    Log.w("ClientHandler-stopAction", e.getMessage());
    }
    try {
    if (thrSend.isAlive()) {
    synchronized (this) {
    notify();
    }
    }
    thrSend.join();
    } catch (InterruptedException e) {
    Log.w("ClientHandler-stopAction", e.getMessage());
    }
    }
    }