① socket java 源代碼
很久以前做的了,啟動程序兩次,在單選框中選伺服器點連接(一定要先點伺服器-連接),在在另外一個界面中選客戶端點連接;
import java.awt.Color;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class QQ extends JFrame implements ActionListener{
public static void main(String args[]){
QQ qq=new QQ();
}
String input;
ServerSocket ss;
Socket s1,s2;
PrintWriter pw;
BufferedReader br;
private server s;
private client cc;
private JLabel l1,l2,l3,l4,l5;
private JRadioButton jb[]=new JRadioButton[2];
private JTextField jf1,jf2,jf3;
private JButton j1,j2,j3;
private JTextArea ja;
public QQ(){
super("聊天");
Container c=getContentPane();
c.setLayout(null);
l1=new JLabel("TCP通信程序");
l1.setFont(new Font("宋體",Font.BOLD,16));
l1.setBackground(Color.black);
l1.setSize(2000,20);
l1.setLocation(10,10);
c.add(l1);
String str1[]={"服務端","客戶端"};
ButtonGroup bg=new ButtonGroup();
for(int x=0;x<str1.length;x++)
{
jb[x]=new JRadioButton(str1[x]);
jb[x].setFont(new Font("宋體",Font.BOLD,15));
jb[x].setForeground(Color.black);
jb[x].setSize(80,40);
jb[x].setLocation(10+x*80,37);
bg.add(jb[x]);
c.add(jb[x]);
}
jb[0].setSelected(true);
l2=new JLabel("連接主機IP");
l2.setFont(new Font("宋體",Font.BOLD,16));
l2.setBackground(Color.black);
l2.setSize(120,20);
l2.setLocation(20, 80);
c.add(l2);
jf1=new JTextField("127.0.0.1");
jf1.setSize(220,30);
jf1.setLocation(120, 80);
c.add(jf1);
jf3=new JTextField("離線");
jf3.setSize(150,30);
jf3.setLocation(280, 40);
c.add(jf3);
l5=new JLabel("連接狀態:");
l5.setFont(new Font("宋體",Font.BOLD,16));
l5.setBackground(Color.black);
l5.setSize(120,20);
l5.setLocation(200, 47);
c.add(l5);
j1=new JButton("連接");
j1.setSize(110,20);
j1.setLocation(360,85);
j1.addActionListener(this);
c.add(j1);
l3=new JLabel("接收到的信息");
l3.setFont(new Font("宋體",Font.BOLD,16));
l3.setBackground(Color.black);
l3.setSize(120,20);
l3.setLocation(20, 130);
c.add(l3);
ja=new JTextArea();
ja.setSize(250,200);
ja.setLocation(130, 130);
c.add(ja);
l4=new JLabel("發送信息");
l4.setFont(new Font("宋體",Font.BOLD,16));
l4.setBackground(Color.black);
l4.setSize(120,20);
l4.setLocation(20, 340);
c.add(l4);
jf2=new JTextField("gf");
jf2.setSize(220,30);
jf2.setLocation(120, 340);
c.add(jf2);
j2=new JButton("發送信息");
j2.setSize(110,20);
j2.setLocation(360,350);
j2.addActionListener(this);
c.add(j2);
j3=new JButton("結束連接");
j3.setSize(110,20);
j3.setLocation(360,110);
j3.addActionListener(this);
c.add(j3);
s=new server();
cc=new client();
j3.setEnabled(false);
j2.setEnabled(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,450);
setVisible(true);
setLocation(300,300);
}
public void actionPerformed(ActionEvent e) {
// TODO 自動生成方法存根
if(e.getSource()==j1)
{
try{
if(jb[0].isSelected()==true)
{
input="";
s.start();
}
else {
input="";
cc.start();
}
}
catch(Exception ee)
{
jf3.setText("發生錯誤");
}
}
if(e.getSource()==j2)
{
pw.write(jf2.getText()+"\n");
pw.flush();
}
if(e.getSource()==j3)
{
try
{
if(jb[0].isSelected()==true)
{ s1.close();
jf3.setText("離線");
j2.setEnabled(false);
j3.setEnabled(false);
}
else
{
s2.close();
jf3.setText("離線");
j2.setEnabled(false);
j3.setEnabled(false);
}
}
catch (Exception e1) {
// TODO 自動生成 catch 塊
}
}
}
class server extends Thread{
public void run(){
try {
j1.setEnabled(false);
jf3.setText("正在連接中@");
ss=new ServerSocket(4000);
s1=ss.accept();
br=new BufferedReader(new InputStreamReader(s1.getInputStream()));
pw=new PrintWriter(s1.getOutputStream(),true);
// bs=new BufferedOutputStream(os);
while(true){
if(ss.isBound()==true){
jf3.setText("連接成功");
j2.setEnabled(true);
j3.setEnabled(true);
break;
}
}
while(true)
{
input=br.readLine();
if(input.length()>0){
ja.append(input);
ja.append("\n");
}
}
} catch (Exception e) {
// TODO 自動生成 catch 塊
}
}
}
class client extends Thread{
public void run(){
try {
j1.setEnabled(false);
jf3.setText("正在連接中@");
s2=new Socket(InetAddress.getByName(jf1.getText()),4000);
// s2=new Socket();
// s2.connect(new InetSocketAddress(jf1.getText(),21),1000);
br=new BufferedReader(new InputStreamReader(s2.getInputStream()));
pw=new PrintWriter(s2.getOutputStream(),true);
// bs=new BufferedOutputStream(os);
while(true){
if(s2.isConnected()==true){
jf3.setText("連接成功");
j2.setEnabled(true);
j3.setEnabled(true);
break;
}
}
input="";
while(true){
input=br.readLine();
if(input.length()>0)
{
ja.append(input);
}
}
} catch (Exception e) {
// TODO 自動生成 catch 塊
}
}
}
}
② 在android端使用socket傳輸圖片到java伺服器,求源代碼
/**
*思想:
1.直接將所有數據安裝位元組數組發送
2.對象序列化方式
*/
/**
*thread方式
*
*@authorAdministrator
*/
{
privatestaticfinalintFINISH=0;
privateButtonsend=null;
privateTextViewinfo=null;
privateHandlermyHandler=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
switch(msg.what){
caseFINISH:
Stringresult=msg.obj.toString();//取出數據
if("true".equals(result)){
TestSocketActivity4.this.info.setText("操作成功!");
}else{
TestSocketActivity4.this.info.setText("操作失敗!");
}
break;
}
}
};
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_test_sokect_activity4);
//StrictMode.setThreadPolicy(newStrictMode.ThreadPolicy.Builder()
//.detectDiskReads().detectDiskWrites().detectNetwork()
//.penaltyLog().build());
//StrictMode.setVmPolicy(newStrictMode.VmPolicy.Builder()
//.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
//.penaltyLog().penaltyDeath().build());
this.send=(Button)super.findViewById(R.id.send);
this.info=(TextView)super.findViewById(R.id.info);
this.send.setOnClickListener(newSendOnClickListener());
}
{
@Override
publicvoidonClick(Viewv){
try{
newThread(newRunnable(){
@Override
publicvoidrun(){
try{
//1:
Socketclient=newSocket("192.168.1.165",9898);
//2:
ObjectOutputStreamoos=newObjectOutputStream(
client.getOutputStream());
//3:
UploadFilemyFile=SendOnClickListener.this
.getUploadFile();
//4:
oos.writeObject(myFile);//寫文件對象
//oos.writeObject(null);//避免EOFException
oos.close();
BufferedReaderbuf=newBufferedReader(
newInputStreamReader(client
.getInputStream()));//讀取返回的數據
Stringstr=buf.readLine();//讀取數據
Messagemsg=TestSocketActivity4.this.myHandler
.obtainMessage(FINISH,str);
TestSocketActivity4.this.myHandler.sendMessage(msg);
buf.close();
client.close();
}catch(Exceptione){
Log.i("UploadFile",e.getMessage());
}
}
}).start();
}catch(Exceptione){
e.printStackTrace();
}
}
()throwsException{//包裝了傳送數據
UploadFilemyFile=newUploadFile();
myFile.setTitle("tangcco安卓之Socket的通信");//設置標題
myFile.setMimeType("image/png");//圖片的類型
Filefile=newFile(Environment.getExternalStorageDirectory()
.toString()
+File.separator
+"Pictures"
+File.separator
+"b.png");
InputStreaminput=null;
try{
input=newFileInputStream(file);//從文件中讀取
ByteArrayOutputStreambos=newByteArrayOutputStream();
bytedata[]=newbyte[1024];
intlen=0;
while((len=input.read(data))!=-1){
bos.write(data,0,len);
}
myFile.setContentData(bos.toByteArray());
myFile.setContentLength(file.length());
myFile.setExt("png");
}catch(Exceptione){
throwe;
}finally{
input.close();
}
returnmyFile;
}
}
}{
privateStringtitle;
privatebyte[]contentData;
privateStringmimeType;
privatelongcontentLength;
privateStringext;
publicStringgetTitle(){
returntitle;
}
publicvoidsetTitle(Stringtitle){
this.title=title;
}
publicbyte[]getContentData(){
returncontentData;
}
publicvoidsetContentData(byte[]contentData){
this.contentData=contentData;
}
publicStringgetMimeType(){
returnmimeType;
}
publicvoidsetMimeType(StringmimeType){
this.mimeType=mimeType;
}
publiclonggetContentLength(){
returncontentLength;
}
publicvoidsetContentLength(longcontentLength){
this.contentLength=contentLength;
}
publicStringgetExt(){
returnext;
}
publicvoidsetExt(Stringext){
this.ext=ext;
}
}
下邊是服務端
publicclassMain4{
publicstaticvoidmain(String[]args)throwsException{
ServerSocketserver=newServerSocket(9898);//伺服器端埠
System.out.println("服務啟動........................");
booleanflag=true;//定義標記,可以一直死循環
while(flag){//通過標記判斷循環
newThread(newServerThreadUtil(server.accept())).start();//啟動線程
}
server.close();//關閉伺服器
}
}
{
="D:"+File.separator+"myfile"
+File.separator;//目錄路徑
privateSocketclient=null;
privateUploadFileupload=null;
publicServerThreadUtil(Socketclient){
this.client=client;
System.out.println("新的客戶端連接...");
}
@Override
publicvoidrun(){
try{
ObjectInputStreamois=newObjectInputStream(
client.getInputStream());//反序列化
this.upload=(UploadFile)ois.readObject();//讀取對象//UploadFile需要和客戶端傳遞過來的包名類名相同,如果不同則會報異常
System.out.println("文件標題:"+this.upload.getTitle());
System.out.println("文件類型:"+this.upload.getMimeType());
System.out.println("文件大小:"+this.upload.getContentLength());
PrintStreamout=newPrintStream(this.client.getOutputStream());//BufferedWriter
out.print(this.saveFile());//返回響應
// BufferedWriterwriter=null;
// writer.write("");
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
this.client.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
privatebooleansaveFile()throwsException{//負責文件內容的保存
/**
*java.util.UUID.randomUUID():
*UUID.randomUUID().toString()是javaJDK提供的一個自動生成主鍵的方法。UUID(Universally
*UniqueIdentifier)全局唯一標識符,是指在一台機器上生成的數字,它保證對在同一時空中的所有機器都是唯一的,
*是由一個十六位的數字組成
*,表現出來的形式。由以下幾部分的組合:當前日期和時間(UUID的第一個部分與時間有關,如果你在生成一個UUID之後,
*過幾秒又生成一個UUID,
*則第一個部分不同,其餘相同),時鍾序列,全局唯一的IEEE機器識別號(如果有網卡,從網卡獲得,沒有網卡以其他方式獲得
*),UUID的唯一缺陷在於生成的結果串會比較長,字元串長度為36。
*
*UUID.randomUUID().toString()是javaJDK提供的一個自動生成主鍵的方法。UUID(Universally
*UniqueIdentifier)全局唯一標識符,是指在一台機器上生成的數字,它保證對在同一時空中的所有機器都是唯一的,
*是由一個十六位的數字組成,表現出來的形式
*/
Filefile=newFile(DIRPATH+UUID.randomUUID()+"."
+this.upload.getExt());
if(!file.getParentFile().exists()){
file.getParentFile().mkdir();
}
OutputStreamoutput=null;
try{
output=newFileOutputStream(file);
output.write(this.upload.getContentData());
returntrue;
}catch(Exceptione){
throwe;
}finally{
output.close();
}
}
}{
privateStringtitle;
privatebyte[]contentData;
privateStringmimeType;
privatelongcontentLength;
privateStringext;
publicStringgetTitle(){
returntitle;
}
publicvoidsetTitle(Stringtitle){
this.title=title;
}
publicbyte[]getContentData(){
returncontentData;
}
publicvoidsetContentData(byte[]contentData){
this.contentData=contentData;
}
publicStringgetMimeType(){
returnmimeType;
}
publicvoidsetMimeType(StringmimeType){
this.mimeType=mimeType;
}
publiclonggetContentLength(){
returncontentLength;
}
publicvoidsetContentLength(longcontentLength){
this.contentLength=contentLength;
}
publicStringgetExt(){
returnext;
}
publicvoidsetExt(Stringext){
this.ext=ext;
}
}
③ C# socket 聊天的 C/s程序 源碼
//"開始"按鈕事件
privatevoidbutton1_Click(objectsender,System.EventArgse){
//取得預保存的文件名
stringfileName=textBox3.Text.Trim();
//遠程主機
stringhostName=textBox1.Text.Trim();
//埠
intport=Int32.Parse(textBox2.Text.Trim());
//得到主機信息
IPHostEntryipInfo=Dns.GetHostByName(hostName);
//取得IPAddress[]
IPAddress[]ipAddr=ipInfo.AddressList;
//得到ip
IPAddressip=ipAddr[0];
//組合出遠程終結點
IPEndPointhostEP=newIPEndPoint(ip,port);
//創建Socket實例
Socketsocket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
try
{
//嘗試連接
socket.Connect(hostEP);
}
catch(Exceptionse)
{
MessageBox.Show("連接錯誤"+se.Message,"提示信息
,MessageBoxButtons.RetryCancel,MessageBoxIcon.Information);
}
//發送給遠程主機的請求內容串
stringsendStr="GET/HTTP/1.1 Host:"+hostName+
" Connection:Close ";
//創建bytes位元組數組以轉換發送串
byte[]bytesSendStr=newbyte[1024];
//將發送內容字元串轉換成位元組byte數組
bytesSendStr=Encoding.ASCII.GetBytes(sendStr);
try
{
//向主機發送請求
socket.Send(bytesSendStr,bytesSendStr.Length,0);
}
catch(Exceptionce)
{
MessageBox.Show("發送錯誤:"+ce.Message,"提示信息
,MessageBoxButtons.RetryCancel,MessageBoxIcon.Information);
}
//聲明接收返回內容的字元串
stringrecvStr="";
//聲明位元組數組,一次接收數據的長度為1024位元組
byte[]recvBytes=newbyte[1024];
//返回實際接收內容的位元組數
intbytes=0;
//循環讀取,直到接收完所有數據
while(true)
{
bytes=socket.Receive(recvBytes,recvBytes.Length,0);
//讀取完成後退出循環
if(bytes〈=0)
break;
//將讀取的位元組數轉換為字元串
recvStr+=Encoding.ASCII.GetString(recvBytes,0,bytes);
}
//將所讀取的字元串轉換為位元組數組
byte[]content=Encoding.ASCII.GetBytes(recvStr);
try
{
//創建文件流對象實例
FileStreamfs=newFileStream(fileName,FileMode.OpenOrCreate,FileAccess.ReadWrite);
//寫入文件
fs.Write(content,0,content.Length);
}
catch(Exceptionfe)
{
MessageBox.Show("文件創建/寫入錯誤:"+fe.Message,"提示信息",MessageBoxButtons.RetryCancel,MessageBoxIcon.Information);
}
//禁用Socket
socket.Shutdown(SocketShutdown.Both);
//關閉Socket
socket.Close();
}
}
④ android socket 編程,用java可以實現的伺服器端,現在要復制源碼到android平台上,可跟客戶端連不上
因為你把連接都寫在了主線程中,主線程的操作不能超過5秒,否則就報錯了,所以你需要在button的點擊事件中另開一個線程去做連接的操作,這樣就不會出現錯誤了
⑤ 兄弟。能發下Android 通過Socket與PC(服務端)通信 的完成源代碼,收到!給分。
這個實驗我是用兩台pc做的實驗,沒有用真機,用的是emule,總體效果感覺可以
大致的思路是這樣的
socket的通信分兩種一種是 tcp另一種是udp,這個之間的通信方式我就不多說了,
主要的重點是許可權的android.premisson,INTERNET
tcp
new Socket();
......
udp
new DatagramSocket();
......
⑥ 您的 安卓基於wifi的對講機用的是UDPsocket傳輸的 源碼可以發給我嘛 包括xml文件 非常感謝82254887
額。。現在給不了了。。我的筆記本被偷了。。所有的資料都丟了。。。界面很簡單,你看到的那個代碼就是全部的,裡面聲明的部件就是全部的界面部件,貌似就兩個editview,開始按鈕,結束按鈕,和退出按鈕(我忘了)。。。當時我也是在學習而已。。再有就是配置AndroidManifest.xml,只記得配置了網路許可權,還有audio許可權。。還有什麼就忘了。。不好意思,幫不了你了
⑦ android服務端與電腦pc上c++的客戶端 實現socket通信
1、android上的伺服器分兩種:
① 用 java 寫的,這種比較簡單,但是需要注意的它的代碼已經被轉換成了大端了,pc上用c++寫傳結構體;
② 用 c/c++ 寫的,這種方式進行和pc上的通信比較的方便,客戶端和伺服器段可以都通過結構來傳遞,唯一需要考慮的是位元組對其的問題,可以用兩個預處理指令(可以跨平台的)處理;
2、源碼的話,我雖然有但是屬於公司的項目代碼,不方便的;
我是ndk吧的吧主,希望大家關注一下ndk吧,有問題的話也可以到裡面留言哦,ndk吧的鏈接:
http://tieba..com/f?kw=ndk 謝謝!
⑧ 如何用socket實現android手機與手機之間的通信
參考一般的JAVA的socket編程,如果通過手機網路,就不要使用UDP即可。
⑨ 有沒有安卓的socket編程的相關資料和源代碼,還有相關書籍,麻煩給推薦下
《瘋狂Android講義》這部書非常好。
有源代碼,而且講解也比較透徹。
如果有有一定java基礎,懂得一些XML的學習效果會更好。