2 asasdadsadwqe asasdadsadwqe 于 2016.09.06 16:39 提问

socket技术客户端发送消息服务器为什么收不到?

服务器:
package com.ouc.textmyserversocket.main;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JOptionPane;

public class Main {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    new ServerListener().start();
}

}
package com.ouc.textmyserversocket.main;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JOptionPane;

public class ServerListener extends Thread {

public void run(){
    try {
        ServerSocket serverSocket = new ServerSocket(54454);
        while(true){
            Socket socket = serverSocket.accept();
            JOptionPane.showMessageDialog(null, "链接54454端口");
            chatSocket cs = new chatSocket(socket);
            cs.start();
            chatManager.getchatManager().add(cs);
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}
package com.ouc.textmyserversocket.main;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;

public class chatSocket extends Thread {
Socket socket;
public chatSocket(Socket s){
this.socket = s;
}
public void out(String out){
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
bw.write(out);
bw.flush();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

public void run(){
    try {
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
        String line = null;
        while((line = br.readLine())!=null){
            chatManager.getchatManager().publish(this,line);
        }
        br.close();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }



}

}package com.ouc.textmyserversocket.main;

import java.util.Vector;

public class chatManager {
private chatManager (){};
private final static chatManager cm = new chatManager();
public static chatManager getchatManager(){
return cm;
}
Vector vector = new Vector ();
public void add(chatSocket cs){
vector.add(cs);
}
public void publish(chatSocket cs,String out ){
for(int i=0;i<vector.size();i++){
chatSocket cschatSocket = vector.get(i);
if( !cs.equals(cschatSocket)){
cschatSocket.out(out);
}
}
}
}
客户端:

package com.example.at;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Xml.Encoding;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
EditText ip;
EditText editText;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ip = (EditText)findViewById(R.id.ip);
editText = (EditText)findViewById(R.id.edit);
text = (TextView)findViewById(R.id.text);

    findViewById(R.id.connect).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            connect();
        }


    });
    findViewById(R.id.send).setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            send();
        }
    });


}

Socket socket = null;
BufferedReader reader = null;
BufferedWriter writer = null;
public void connect(){

        AsyncTask<Void,String,Void> read = new AsyncTask<Void,String,Void>(){

            @Override
            protected Void doInBackground(Void... arg0) {
                // TODO Auto-generated method stub
                    try {
                        socket = new Socket(ip.getText().toString(),54454);
                        writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                        reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        publishProgress("@success");
                    } catch (UnknownHostException e) {
                        Toast.makeText(MainActivity.this, "无法建立连接", Toast.LENGTH_SHORT).show();
                    } catch (IOException e) {
                        Toast.makeText(MainActivity.this, "无法建立连接", Toast.LENGTH_SHORT).show();
                    }
                    try {
                        String line;
                        while((line = reader.readLine())!= null){
                            publishProgress(line);

                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                return null;
            }

            @Override
            protected void onProgressUpdate(String... values) {
                // TODO Auto-generated method stub
                if(values[0].equals("@success")){
                    Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();

                }
                text.append("别人说:"+values[0]+"\r\n");
                super.onProgressUpdate(values);
            }

        };
        read.execute();

}
public void send(){
    try {
        text.append("我说:"+editText.getText().toString()+"\r\n");
        writer.write(editText.getText().toString()+"\r\n");
        writer.flush();
        editText.setText("");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
}

1个回答

coding_hello
coding_hello   2016.09.06 20:39

java不太会,说下思路。 首先明确一点,写网络程序,必须会使用报文分析软件,比如wireshark。

客户端和服务端都是你的代码,所以应该先单独测试。比如,服务端运行起来后,用netstat -an 命令查看服务端口是否在listen状态。如果不是,肯定不对。如果是的话,用telnet之类的通用命令尝试连接一下,看是不是能连上。如果能连上,就是server端好着。再用客户端来测试。

一个个来,不要同时测这俩,因为不知道问题在哪个上,可能俩都有问题。

学会用wireshark,在服务端或者客户端上抓包,看看tcp连接过程的报文就能知道是谁的问题。你值得拥有。

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!