安卓socket聊天,端口被占用问题(附:socket聊天代码)(一)

关于端口被占用问题,见下一章,全自动化,无需手动修改


初学者注意:服务器用的是eclipse的web版本(话说我也是初学者哈)

废话不多说,先贴上socket聊天代码

服务器端代码

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


public class Server
{
    public static final int port=8888;
    public static ServerSocket serverSocket;
    public static Socket socket;
    public static ArrayList arraySocket=new ArrayList();
    public static void main(String[] args) throws Exception
    {
int i=0,j=0;
while(true){
   try
   {
    Process process=Runtime.getRuntime().exec("cmd /c start c://Users//think//Desktop//test1.bat");
    process.waitFor();
    Thread.sleep(5000);
   }catch (IOException e)
   {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   try      
   {
    serverSocket=new ServerSocket(port);
    break;
   }
   catch(Exception e)
   {
    System.out.print("错误");
   }
}
while(true)
   {
       System.out.println("正在连接...");
    socket=serverSocket.accept();
    arraySocket.add(socket);
    new Thread(new ServerThread(socket)).start();
    System.out.print(""+i+"......");
    i++;
   }
    }
}
class ServerThread implements Runnable
{
    DataInputStream input;
    Socket socket;
    String str;
    public ServerThread(Socket socket)
    {
this.socket=socket;
    }
    public void run()
    {
   try
   {
input=new DataInputStream(socket.getInputStream());
while((str=input.readUTF())!=null)
{
   for(Socket socket:Server.arraySocket)
   {
DataOutputStream output=new DataOutputStream(socket.getOutputStream());
output.writeUTF(packString(str));
   }
}
   } catch (IOException e)
   {
// TODO Auto-generated catch block
e.printStackTrace();
   }    
    }
    public String packString(String str)
    {
String result=null;
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss"); 
if(str.startsWith("first"))
{
   result="/n"+"sheng:"+df.format(new Date())+str.substring(5);
}
if(str.startsWith("second"))
{
   result="/n"+"hu"+df.format(new Date())+str.substring(6);
}
return result;
}
}

客户端代码如下:

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Build;


public class MainActivity extends Activity 
{
Button button;
TextView textView;
EditText editText;
Content myContent=new Content();
Handler handler=new Handler()
{
public void handleMessage(Message message)
{
if(message.what==1)
{
Log.v("function1","1");
textView.setText(myContent.getContent());
}
}
};

protected void onCreate(Bundle savedInstanceState) 
{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
       
button=(Button)findViewById(R.id.button1);
textView=(TextView)findViewById(R.id.textView1);
editText=(EditText)findViewById(R.id.editText1);
Log.v("function2","2");

new Thread(new Runnable()
{
Socket socket;

public void run()
{
String str;
try 
{
socket = new Socket("10.0.2.2",8888);

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

button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
try 
{
DataOutputStream output=new DataOutputStream(socket.getOutputStream());
output.writeUTF("first"+editText.getText().toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});

try
{
DataInputStream input=new DataInputStream(socket.getInputStream());
while((str=input.readUTF())!=null)
{
myContent.setContent(str);
Message message=new Message();
message.what=1;
handler.sendMessage(message);
}
} catch (IOException e) 
{
e.printStackTrace();
}
}
}).start();

}
}
class Content
{
String content="";
public void setContent(String content)
{
this.content+=content;
}
public String getContent()
{

return content;
}
}


layout相关代码如下(这段代码写在res文件下的layout文件里的activity_main.xml,不熟的先去看一下控件用xml写的相关内容)(虽然很容易,但想想有多少人也跟我当时一样啥也不懂,所以还是详细一点好)

    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
>
   android:id="@+id/textView1"
   android:layout_width="match_parent"
   android:layout_height="50dp"
   />
   android:id="@+id/editText1"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   />
    android:id="@+id/button1"
    android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送"
/>

这些代码,根据真实故事改编,本段代码感谢”依旧淡然“兄,故事入口如下(里面有详细讲解):http://www.cnblogs.com/menlsh/archive/2013/06/12/3133296.html

注:本代码瑕疵:

1.有很多import,import中有许多多余,都是打代码过程中的实验品,大家可以不去看它

2.没有连接数据库,只是拿了两个固定的人物”hu“,”sheng”进行对话,看懂后可以自行修改,这也是本段代码的优点,比较方便,粘贴了就可以用

3.没有处理socket关闭问题,我比较笨,关闭先不管了。。。



你可能感兴趣的:(安卓,复习)